- 關(guān)鍵字:最長不重復(fù)子串、雙指針
- 難度:Medium
- 題目大意:求一個字符串最長不重復(fù)子串的長度
題目:
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.
思路:
使用兩個指針l、r分別記錄不重復(fù)子串的起始和終止位置,l、r初始值為0,使用set來放當(dāng)前不重復(fù)的字符,r向右移動:
- 字符不重復(fù)時,直接將字符add到set,r繼續(xù)向右移動;
- 字符重復(fù)時,l向右移動,同時set刪除掉字符串l位置的字符;
- 重復(fù)上述步驟;
思路實現(xiàn):
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()==0||s==null) return 0;
int maxLen = 1;
int l = 0;
int r = 1;
Set<Character> set = new HashSet<>();
set.add(s.charAt(l));
while(l<s.length()&&r<s.length()) {
if(!set.contains(s.charAt(r))) {
set.add(s.charAt(r));
maxLen = Math.max(maxLen, r-l+1);
r++;
}
else {
set.remove(s.charAt(l));
l++;
}
}
return maxLen;
}
}