zoukankan      html  css  js  c++  java
  • 无重复字符的最长字串(C++,python实现)

    C++代码:

    #include<iostream>
    #include<unordered_set>
    #include<string>
    using::std::unordered_set;
    using::std::string;
    using::std::max;
    class Solution{
    public:
      unordered_set<char> slen;
      int lengthoflongestsubstring(string s)
      {
        int p=-1,len=0;
        int n = s.size();
        for(int i=0;i<n;i++)
        {
          if(i!=0)
          {
            slen.erase(s[i-1]);
          }
          while(p+1<n&&!slen.count(s[p+1]))
          {
            slen.insert(s[p+1]);
            p++;
          }
          len = max(len,p-i+1);
        }
        std::cout << len << ' ';
        return len;
    }
    };
    int main()
    {
      Solution sol;
      string s = "abcdefab";
      sol.lengthoflongestsubstring(s);
      return 0;
    }
     
    测试结果:
     

     python代码实现:

    class Solution:
        def lengthoflongestsubstring(self,s:str):
            a = set()
            n = len(s)
            rk,ans = -1,0
            for i in range(n):
                if i!=0:
                    a.remove(s[i-1])
                while rk + 1 < n and s[rk+1] not in a:
                    a.add(s[rk+1])
                    rk += 1
                ans = max(ans,rk-i+1)
            print(ans)
            return ans
    s = "abcdfea"
    foo = Solution()
    foo.lengthoflongestsubstring(s)
     
    测试结果:

  • 相关阅读:
    boost::timer库使用
    List的子类特点
    Exception in thread "main" java.util.ConcurrentModificationException解决方案
    Java中的集合Collection
    数组和集合的区别
    jsp 九大内置对象
    include指令与jsp:include动作标识的区别
    idea 2018注册码(激活码)
    内存的页面置换算法
    MYSQL的两种存储引擎区别
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13584675.html
Copyright © 2011-2022 走看看