//滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) return 0;
HashMap<Character, Integer> map = new HashMap<>();
int result = 0;
int max = 0;
int left = 0;
for (int i = 0; i < s.length(); i++) {
//如果当前字符不在map里面,max加1,把字符加进map
if (!map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), i);
} else {
//定义左边界,这里要和left比较,不然abba这种会错误
//left = map.get(s.charAt(i)) + 1;
left = Math.max(left, map.get(s.charAt(i)) + 1);
//把map里面当前字符的key的value更新为当前地址
map.put(s.charAt(i), i);
}
max = i - left + 1;
result = Math.max(max, result);
}
return result;
}
}
leetcode3. 无重复字符的最长子串
最新推荐文章于 2024-01-11 19:22:57 发布