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;
}
}