[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;
    }
}
posted @ 2023-12-04 14:50  Ac_c0mpany丶  阅读(11)  评论(0)    收藏  举报