给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
思路:滑动窗口
扩张条件:i -> j范围内,map中字符的最大频率maxFre <= 1
- j ++
滑动条件:maxFre > 1
- i++
code
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0 || s.length() == 0) {
return s.length();
}
Map<Character, Integer> map = new HashMap<>();
int res = 1;
int i = 0;
map.put(s.charAt(0), 1);
for (int j = 1; j < s.length(); j++) {
char c = s.charAt(j);
map.merge(c, 1, Integer::sum);
int maxFre = getMaxFre(map);
if (maxFre <= 1) {
res = Math.max(res, j - i + 1);
} else {
Integer fre = map.get(s.charAt(i));
map.put(s.charAt(i), fre - 1);
i++;
}
}
return res;
}
private int getMaxFre(Map<Character, Integer> map) {
return map.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
}
}