标签:
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