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协议。
  • 相关阅读:
    解决Struts中文乱码问题总结
    多校第十场1009 CRB and String题解
    DirectX--Filter属性页的调用
    理解ThreadLocal类
    unity3d
    使用Java8提供的Duration类制作字幕时间轴调整工具
    算法练习--卡片游戏
    在eclipse中创建web项目
    testNg官方文档
    TestNG基本注解(注释)
  • 原文地址:https://www.cnblogs.com/yejianying/p/leetcode_3.html
Copyright © 2011-2022 走看看