LEETCODE_3_无重复字符的最长子串

本文介绍了一种高效求解最长无重复字符子串的方法,使用HashMap存储字符及其索引,通过一次遍历即可得到结果,时间复杂度为O(n)。

 题目:


Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.


 

思路:

第一种方法:

依次从第一个、第二个...最后一个字符,找无重复字符串,计算长度,比较大小

这种方法无法通过,因为超时了。

 

第二种方法:

思路:找无重复字符串,即找到两个相同字符之间的字符串长度。

需要解决的问题:如何保证两个字符之间没有其他重复的字符 

详细思路:


 

利用HashMap存放字符与对应的索引

1,设置start指向不重复串的第一个位置,假设start指向字符a

2,再次遇到a时,如果之前a的索引大于或等于start值,令start指向第一个a的索引值加1,并令map中a的value值更新

3,此时,两个a之间的字符串就是不重复字符串,它的值为: 当前a的位置-start+1

注意: 之所以要比较start值与第一个a的索引是因为,如果start值大于第一个a的索引值,则在两个a之间必定已经存在其他重复的字符,只有这种情况start值才可能比第一个a的索引值大,(保证start是一直增大的)

时间复杂度O(n)


 

代码:

public int lengthOfLongestSubstring(String s) {
         
         HashMap<Character, Integer> map = new HashMap<>();
         int start = 0;
         int len = 0;
         int maxLen = 0;
     
         for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i)) && map.get(s.charAt(i))>=start) {
                start = map.get(s.charAt(i))+1;
            }
            len = i-start+1;
            map.put(s.charAt(i), i);
            
            if (len>=maxLen) {
                maxLen = len;
            }
        }     
         return maxLen;
     }

 

转载于:https://www.cnblogs.com/wkcode/p/8697602.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值