给定一个字符串,找出不含有重复字符的最长子串的长度。
示例:
给定 "abcabcbb"
,没有重复字符的最长子串是 "abc"
,那么长度就是3。
给定 "bbbbb"
,最长的子串就是 "b"
,长度是1。
给定 "pwwkew"
,最长子串是 "wke"
,长度是3。请注意答案必须是一个子串,"pwke"
是 子序列 而不是子串。
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> pos = new HashMap<>();
char[] ss = s.toCharArray();
int max = 0, temp = 0;
for(int i = 0; i < s.length(); i++){
if( !pos.containsKey(ss[i]) ){
pos.put(ss[i],i);
temp++;
}else{
if(pos.get(ss[i]) + temp < i){
temp++;
}else{
max = Math.max(max,temp);
temp = i - pos.get(ss[i]);
}
pos.put(ss[i],i);
}
}
max = Math.max(max,temp);
return max;
}
}