【题目】
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.
【思路】
滑动窗口Sliding Window
【代码】
update 8.22:https://www.bilibili.com/video/BV1ub4y1d7Z8
右边指针一直向前,如果遇到已经存在数组的数,证明之前已遍历过(在左边)。ds.containsKey(s.charAt(right))
于是考虑左指针逼近,如果现在的左指针>此数上次出现的位置,不再更新,反之更新指针
class Solution { public int lengthOfLongestSubstring(String s) { int ans=0;int left=0; Map<Character,Integer> ds=new HashMap<>(); for(int right=0;right<s.length();right++){ if(ds.containsKey(s.charAt(right))) left=Math.max(left,ds.get(s.charAt(right))+1); ds.put(s.charAt(right),right); ans=Math.max(ans,right-left+1); } return ans; } }
public class Solution {
public int lengthOfLongestSubstring(String s) {
int len=s.length();
int ans=0;int j=0;
Map<Character,Integer> map=new HashMap<>();
for(int i=0;i<len;i++){
if(map.containsKey(s.charAt(i))){
j=Math.max(j,map.get(s.charAt(i)));
}
ans=Math.max(ans,i-j+1);
map.put(s.charAt(i),i+1);
}
return ans;
}
}