Requirement
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, which the length is 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.
我一看到题目的想法是用一个哈希集合存储顺序遍历到的字符,遇到已存在哈希集合的字符时记录下哈希集合的大小与之前的结果进行比较,较大者作为暂时的结果,然后清空哈希集合,存储当前字符,继续循环直到遍历字符串结束。但是,这是一个错误的想法,对于无重复字符的字符串其得到的结果永远为0,还有应该从重复字符的前者的下一个字符开始而不是从后者开始。例如,字符串”dvdf”,应该从’v’开始而不是从第二个’d’开始否则会得到错误答案。进过分析之后,发现滑动窗口算法Sliding Window是一个不错的算法,故解决方法基于滑动窗口算法。
下面提供一种解决方法:
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> map=new HashMap<>();
int res=0;
for(int i=0,j=0;j<s.length();++j){
if(map.containsKey(s.charAt(j)){
i=Math.max(i,map.get(s.charAt(j)+1);
}
res=Math.max(res,j-i+1);
map.put(s.charAt(j),j);
}
return res;
}
}