美文网首页
[LeetCode][M] 3. 无重复字符的最长子串

[LeetCode][M] 3. 无重复字符的最长子串

作者: 埋没随百草 | 来源:发表于2019-07-24 00:42 被阅读0次

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    示例 1:

    输入: "abcabcbb"
    输出: 3
    解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

    示例 2:

    输入: "bbbbb"
    输出: 1
    解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

    示例 3:

    输入: "pwwkew"
    输出: 3
    解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
    请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

    解题思路

    滑动窗口法,时间复杂度为O(n)。
    使用end指针从左到右遍历所有字符,start最开始指向第1个字符的位置。遍历到end位置的字符时,如果可以从map中找到该位置的字符,则更新start指针的位置。每次遍历都更新ans,以及把当前位置的字符放入map。

    实现代码

    //执行用时 :29 ms, 在所有 Java 提交中击败了57.04%的用户
    //内存消耗 :38.7 MB, 在所有 Java 提交中击败了86.35%的用户
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int ans = 0;
            Map<Character, Integer> map = new HashMap<>();
            for (int end = 0, start = 0; end < s.length(); end++) {
                if (map.containsKey(s.charAt(end))) {
                    start = Math.max(start, map.get(s.charAt(end)));
                }
                ans = Math.max(ans, end - start + 1);
                map.put(s.charAt(end), end + 1);
            }
            return ans;
        }
    }
    

    C++:

    //执行用时 :16 ms, 在所有 C++ 提交中击败了81.58%的用户
    //内存消耗 :8.9 MB, 在所有 C++ 提交中击败了97.16%的用户
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int ans = 0;
            int hash[256] = {0};
            for (int end = 0, start = 0; end < s.size(); end++) {
                if (hash[s[end]] != 0) {
                    start = max(start, hash[s[end]]);
                }
                
                ans = max(ans, end - start + 1);
                hash[s[end]] = end + 1;
            }
            
            return ans;
        }
    };
    

    相关文章

      网友评论

          本文标题:[LeetCode][M] 3. 无重复字符的最长子串

          本文链接:https://www.haomeiwen.com/subject/txzzlctx.html