题目描述:
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.
本题要求给定一字符串,求出最长的不含重复字符的子串。首先想到顺序遍历每一个字符,求出以该字符为首字符的子串长度,再求出最大值。这样需要三个for循环,时间复杂度为O(n³)。现在简化求子串长度这一过程。在顺序遍历时建立一哈希表,储存某字符出现的位置。再次遍历即可得出某字符的下一个相同字符的位置(如果不存在则为∞)与以该字符为起点,最长子串终点的位置。
代码如下:
int lengthOfLongestSubstring(string s) {
if(s=="")
return 0;
int size = s.size();
vector<int> repeatingPos;
vector<list<int> > hashOfStr(256);
for(int i=0;i<size;i++)
hashOfStr[(int)s[i]].push_back(i);
for(int i=0;i<size;i++)
{
hashOfStr[(int)s[i]].pop_front();
repeatingPos.push_back(hashOfStr[(int)s[i]].empty() ? size : hashOfStr[((int)s[i])].front());
}
int maxPos=repeatingPos[size-1];
for(int i=size-1;i>=0;i--)
{
if(repeatingPos[i]<maxPos)
maxPos=repeatingPos[i];
else
repeatingPos[i]=maxPos;
}
for(int i=0;i<size;i++)
repeatingPos[i]-=i;
return *max_element(repeatingPos.begin(),repeatingPos.end());
}