Leetcode #3 Longest Substring Without Repeating Characters

来源:互联网 发布:青苹果软件 编辑:程序博客网 时间:2024/04/28 18:36

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

借鉴了别人的思路,采用双指针,结合map


#include<map>


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        int maxlength =1;
        map<char,int> mymap;
        
        
        
        if(s.length()==0)
        return 0;
        if(s.length()==1)
        return 1;
        
        int start = -1;
        
        for(int i=0;i<s.length();++i)
        {
            if(mymap.count(s[i])==0)
            {
                mymap.insert(make_pair(s[i],i));
            }
            else
            {
                
                if(mymap[s[i]]>start)    //Important, we only care elements in our sliding window
                  start = mymap[s[i]];
                mymap[s[i]] = i;
                
                
                
            }
            
            if(i-start >maxlength)
               maxlength = i-start;
        }
        
        return maxlength;
    }
};

0 0