题目描述:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201112192827949.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTAwOTU5,size_16,color_FFFFFF,t_70#pic_center)
参考代码:
public int lengthOfLongestSubstring(String s) {
int ans=0;
Map<Character,Integer> map=new HashMap<>();
for (int end = 0,start=0; end <s.length() ; end++) {
char c=s.charAt(end);
if(map.containsKey(c))
start=Math.max(map.get(c),start);
ans=Math.max(ans,end-start+1);
map.put(c,end+1);
}
return ans;
}
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> map=new HashMap<>();
char[] c=s.toCharArray();
int max=0;
int left=0;
if(s.length()<2)
return s.length();
map.put(c[0],0);
for (int i = 1; i < s.length(); i++) {
if(map.containsKey(c[i]))
{
left=Math.max(left,map.get(c[i])+1);
}
map.put(c[i],i);
max=Math.max(max,i-left+1);
}
return max;
}