Leetcode3. 无重复字符的最长子串

方法一(自写)暴力法   时间复杂度:O(n^2)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int count1=0;
        for(int i=0;i<s.length();i++)
        {
            vector<char> v;
            int t=0;
            v.push_back(s[i]);
            t++;
            for(int j=i+1;j<s.length();j++)
            {
               
                if(count(v.begin(),v.end(),s[j])>0)
                    break;
                else
                {
                     v.push_back(s[j]);
                     t++;
                }
            }
            if(t>count1)
                count1=t;
        }
       return count1;
    }
};

  

方法二:滑动窗口法   时间复杂度:O(2n)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int i=0,j=0,sum=0;
        set<char> num;
        while(i<s.length()&&j<s.length())
        {
            if(num.count(s[j])==0)
            {
             num.insert(s[j++]);  
             if(sum<j-i)
                sum=j-i;
            }
            else
                num.erase(s[i++]);
        }
        return sum;
    }
};

  

 

posted @ 2019-07-15 14:02  saaas  阅读(83)  评论(0)    收藏  举报