题目:
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; }