码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Longest Substring Without Repeating Characters

时间:2014-07-27 10:25:42      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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记录关键信息,得到了O(n)的解法:

class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
           if(s.size()<2)
               return s.size();
           int lengthOfCurrent=1,maxLength = 1; //lengthOfCurrent表示当前字符往前具有的不重复字符个数。
           map<char,int> m;                     //m里存放字符及字符在s中的下标。
           m[s[0]]=0;
           for(int i = 1;i<s.size();i++)
           {
               if(m.count(s[i])==0 || m[s[i]]<i-lengthOfCurrent)//当前字符没与之前重复 或者 重复了但在前一个字符重复字符之前,对当前最大长度没有影响
                   lengthOfCurrent++;
               else
                   lengthOfCurrent = i -  m[s[i]];
               m[s[i]] = i;
               if(lengthOfCurrent>maxLength)
                   maxLength = lengthOfCurrent;

           }


           return maxLength;
        }
    };

 

[LeetCode] Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/Xylophone/p/3870655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!