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.
题解:
使用贪心策略,Hash记录字符上一次出现的位置,并记录起点。
每次更新的时候,记得将start checkpoint 之间出现的字符location清空,以免重复。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int location[],i,index,j;
for(i=;i<;i++) location[i]=-;
int start=,maxLength=,templ=;
for(i=;i<s.size();i++)
{
index = s[i];
if(location[index]== -)
templ++;
else
{
if(templ>maxLength)
{
maxLength = templ;
// cout<<s.substr(start,templ)<<endl;
}
for(j=start;j<location[index];j++)
location[s[j]]=-;
templ =templ - (location[index]-start);
start = location[index]+;
}
location[index]=i;
}
if(i==s.size() && templ>maxLength) maxLength=templ;
return maxLength;
}
};
转载请注明出处: http://www.cnblogs.com/double-win/