• 无重复字符的最长字串(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)
     
    测试结果:

  • 相关阅读:
    安卓学习记录(五)——体温表APP.2
    今日学习
    每日学习
    AS插件快速生成javabean
    LA 5842 Equipment (状态压缩+dp)
    LA 4794 Sharing Chocolate (搜索)
    LA 5844 Leet (dfs 搜索)
    uva 11627 Slalom (二分法)
    ZOJ 3031 Robotruck (dp + 单调队列)
    uva 10012 How Big Is It? (greedy + enumerate)
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13584675.html
Copyright © 2020-2023  润新知