解法一:使用双指针+set
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set=new HashSet<Character>();
int max=0;
for(int i=0,j=0;i<s.length();i++){
while(set.contains(s.charAt(i)))
set.remove(s.charAt(j++));
set.add(s.charAt(i));
max=Math.max(max,set.size());
}
return max;
}
}
解法二:使用map记录上一个出现s.charAt(i)的位置,更新j和max,相比于前面的更新会略快。
class Solution {
public int lengthOfLongestSubstring(String s) {
int max=0;
if(s.length()<=0)
return max;
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0,j=0;i<s.length();i++){
if(map.containsKey(s.charAt(i)))
j=Math.max(j,map.get(s.charAt(i))+1);
map.put(s.charAt(i),i);
max=Math.max(max,i-j+1);
}
return max;
}
}