码迷,mamicode.com
首页 > 其他好文 > 详细

3. Longest Substring Without Repeating Characters - Medium

时间:2019-01-22 10:50:44      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:mat   fast   rem   进入   input   contain   hat   Plan   span   

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

 

3. Longest Substring Without Repeating Characters - Medium

标签:mat   fast   rem   进入   input   contain   hat   Plan   span   

原文地址:https://www.cnblogs.com/fatttcat/p/10301890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!