[LeetCode Hot 100] LeetCode3. 无重复字符的最长子串
题目描述
思路:滑动窗口
- 定义需要维护的变量
// 1. 定义需要维护的变量
int max_len = 0;
Map<Character, Integer> hashmap = new HashMap<>();
- 窗口不满足条件,窗口收缩。窗口不是固定大小所以用while
// 4. 窗口不满足条件: 窗口收缩
// 满足这个条件说明有重复元素
// 这时要用一个while去不断移动窗口左指针,从而剔除非法元素直到窗口再次合法
while (end - start + 1 > hashmap.size()) {
char head = s.charAt(start);
hashmap.put(head, hashmap.get(head) - 1);
if (hashmap.get(head) == 0) {
hashmap.remove(head);
}
start ++;
}
代码一:
class Solution {
public int lengthOfLongestSubstring(String s) {
// 1. 定义需要维护的变量
int max_len = 0;
Map<Character, Integer> hashmap = new HashMap<>();
// 2. 定义窗口
int start = 0;
for (int end = 0; end < s.length(); end ++) {
// 3. 更新参数
char ch = s.charAt(end);
hashmap.put(ch, hashmap.getOrDefault(ch, 0) + 1);
// 窗口满足条件
// 没有出现重复元素
if (end - start + 1 == hashmap.size()) {
max_len = Math.max(max_len, end - start + 1);
}
// 4. 窗口不满足条件: 窗口收缩
// 满足这个条件说明有重复元素
// 这时要用一个while去不断移动窗口左指针,从而剔除非法元素直到窗口再次合法
while (end - start + 1 > hashmap.size()) {
char head = s.charAt(start);
hashmap.put(head, hashmap.get(head) - 1);
if (hashmap.get(head) == 0) {
hashmap.remove(head);
}
start ++;
}
}
return max_len;
}
}
本文作者:Ac_c0mpany丶
本文链接:https://www.cnblogs.com/keyongkang/p/17874916.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步