3. Longest Substring Without Repeating Characters - Medium

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;
    }
}

 

posted @ 2019-01-22 09:11  fatttcat  阅读(127)  评论(0编辑  收藏  举报