class Solution {
public static int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int ans = 0;
int maxLen = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
if (!map.containsKey(s.charAt(i))) {
ans++;
map.put(s.charAt(i), i);
} else {
if (map.get(s.charAt(i)) < start){
ans++;
}else{
ans = i - map.get(s.charAt(i));
start = map.get(s.charAt(i))+1;
}
map.put(s.charAt(i), i);
}
if (ans > maxLen) {
maxLen = ans;
}
}
return maxLen;
}
}
剑指 Offer II 016. 不含重复字符的最长子字符串
最新推荐文章于 2024-07-24 20:44:05 发布