LeetCode-003-无重复字符的最长子串
思路
滑动窗口
题目要求给出最长不重复的连续子串,只需要设置左、右指针,然后通过右指针进行遍历,如果右指针所指的字母在之前出现过,那么把左指针设置为max(左指针,上一个出现过的位置的下一个),使用HashMap来存出现过的字母。
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer>map=new HashMap();
int l=0;
int len=0;
for(int r=0;r<s.length();r++){
if(map.containsKey(s.charAt(r)))
l=Math.max(map.get(s.charAt(r))+1,l);
map.put(s.charAt(r),r);
len=Math.max(len,r-l+1);
}
return len;
}
}