zoukankan      html  css  js  c++  java
  • LeetCode——3. Longest Substring Without Repeating Characters

    题目:

    这里用的是滑动窗口的思路,有两种实现方式:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
         
            unordered_map<char, int> vocab;
            int maxLen = 0;
            int left = -1;
            for(int i=0; i<s.size(); i++){
                if(vocab.count(s[i]) && vocab[s[i]]>left){
                    left = vocab[s[i]];
                }
                vocab[s[i]] = i;
                maxLen = max(maxLen, i - left);
            }
            return maxLen;
        }
    };
    

    注意left = -1,这里是用来应对s.size=" "时的情况的(此时最终输出应为1)。

    上面这种要快一点,思路就是记录每个字母出现的位置,然后根据位置来调整窗口的left指向的位置(即调整窗口大小)。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int maxLen = 0;
            int left = 0;
            unordered_set<char> dict;
      
            for(int i=0; i<s.size(); i++){
                while(dict.find(s[i])!=dict.end()){
                    dict.erase(s[left]);
                    left++;
                }
                maxLen = max(maxLen, i-left+1);
                dict.insert(s[i]);
            }
            return maxLen;
        }
    };
    

    这种的话就是每次都遍历一次窗口,看窗口中有没有重复的字符,如果有那么久将left右移一格,直到窗口中所有字符都唯一。第一种方法就是优化了遍历的这一个步骤,所以更加快一些。

    本博客文章默认使用CC BY-SA 3.0协议。
  • 相关阅读:
    及时说爱
    坚持
    html5新增元素
    js call
    smarty实例教程
    JS 跨浏览器兼容问题
    CSS3中的5个有趣的新技术
    jQuery和dom转化
    前端安全问题
    js apply
  • 原文地址:https://www.cnblogs.com/yejianying/p/leetcode_3.html
Copyright © 2011-2022 走看看