Longest Substring Without Repeating Characters

来源:互联网 发布:matlab 剔除重复数据 编辑:程序博客网 时间:2024/06/05 12:45

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a

substring"pwke" is a subsequence and not a substring.


/*从头扫到尾,每次遇到有两个字符相等就记录当前的最大长度,并更新下一次应该开始记录的位置Last*/class Solution {public:    int lengthOfLongestSubstring(string s) {        map<char,int>M;        int len=s.length();        int tmp=0;        int Last=0;        int ans=1;        int i;        for( i=0;i<len;++i)        {            if(M.find(s[i])==M.end())            {                M.insert(make_pair(s[i],i));            }            else if(M.find(s[i])->second<Last)            {            M.erase(s[i]);            M.insert(make_pair(s[i],i));}            else            {            cout<<i<<" "<<Last<<endl;                ans=max(ans,i-Last);                Last=M[s[i]]+1;                M.erase(s[i]);                M.insert(make_pair(s[i],i));            }        }        cout<<i<<" "<<Last<<endl;        ans=max(ans,i-Last);        if(len==0)ans=0;        return ans;    }};


原创粉丝点击