Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 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.
method 1 sliding window
使用hashSet記錄某個字符是否出現過
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
但是,我們可以對該方法進行優化,我們可以跳過那些已經確定無重複字符的區間,因此使用map替代set,map的value表示key的所在位置
method 2 Sliding Window Optimized
int lengthOfLongestSubstring(string s) {
map<char, int> map;
int maxLength = 0;
int left = 0, right = 0;
while (right < s.size()){
char ch = s[right];
if (!map.count(ch))
map[ch] = right;
else{
maxLength = max(right - left, maxLength);
if (left <= map[ch])
left = map[ch] + 1;
map[ch] = right;
}
right++;
}
return max(maxLength, right - left);
}
以下爲官方solution的簡化版
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
}
以下是借用上一篇文章中提到的模板所模仿的代碼
重點要理解counter的作用,counter表示在區間內重複的字符,因此一旦counter大於0,那麼就要移動左指針,縮小窗口
int lengthOfLongestSubstring(string s) {
vector<int> map(128, 0);
int counter = 0, begin = 0, end = 0;
int d = 0;
while (end < s.size()){
if (map[s[end++]]++ > 0) counter++;
while (counter > 0){
if (map[s[begin++]]-- > 1) counter--;
}
d = max(d, end - begin);
}
return d;
}
summary
- Sliding Window思想,左指針contract window,去除不符合要求的字符,右指針expand window。
- 使用counter計數重複的字符數,一次來作爲左指針移動的指標,值得借鑑
- 使用vector代替map