• 3. Longest Substring Without Repeating Characters


    Given a string, find the length of the longest substring without repeating characters.

    Example 1:

    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    

    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    

    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3. 
                 Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    M1: sliding window + hash map (more generalize)

    用d表示所求substring长度。fast扫描string,存进map。用counter计数,如果map中对应value > 1,counter++。当counter > 0时进入while循环开始移动slow找有效的substring,如果slow所指的字符对应出现次数 > 1,counter--,并存入新的value,slow向右移动。退出while循环时即找到有效substring,此时记录fast - slow,并和d比较,取较大值。

    time: O(n), space: O(n)

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            Map<Character, Integer> map = new HashMap<>();
    
            int slow = 0, fast = 0, counter = 0, d = 0;
            while(fast < s.length()) {
                char c = s.charAt(fast);
                map.put(c, map.getOrDefault(c, 0) + 1);
                if(map.get(c) > 1) {
                    counter++;
                }
                fast++;
                
                while (counter > 0) {
                    char tmp = s.charAt(slow);
                    if (map.get(tmp) > 1) {
                        counter--;
                    }
                    map.put(tmp, map.get(tmp) - 1);
                    slow++;
                }
                d = Math.max(d, fast - slow);
            }
            return d;
        }
    }

    M2: sliding window + hash set (specific to unique character)

    time: O(n), space: O(n)

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            Set<Character> set = new HashSet<>();
    
            int slow = 0, fast = 0, max = 0;
            while(fast < s.length()) {
                if(!set.contains(s.charAt(fast))) {
                    max = Math.max(max, fast - slow + 1);
                    set.add(s.charAt(fast++));
                } else {
                    set.remove(s.charAt(slow++));
                }
            }
            return max;
        }
    }
  • 相关阅读:
    数据结构(2)
    python数据结构(1)
    python 中__getitem__ 和 __iter__ 的区别
    python 中的 %s,%r,__str__,__repr__
    python中的zip
    python反射,单例模式
    类python中高级用法
    python中super与成员属性
    python 类与对象解析
    【其他】BootCDN
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10301890.html
Copyright © 2020-2023  润新知