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.
思路: 求最长不重复子字符串类问题, 可以将字符串按照顺序存放在连续的数组中即可。 在存入的时候判断是否重复,做香烟处理。遍历一次即可得到最长子串。时间复杂度:O(n)
扩展:求最长重复子字符串
#define max(x,y) (x>y)?(x):(y)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> hash(256,-1);
int sMax = 0;
int latestStart = 0;
int start =0;
for(int i= 0;i<s.length();i++)
{
//repeat char
if(hash[s[i]]!= -1)
{
sMax = max(sMax,i-start);
latestStart = start;
start = hash[s[i]]+1;
for(int j = latestStart;j<start;j++)
hash[s[j]] = -1;
}
hash[s[i]] = i;
}
return max(sMax,s.length()-start);
}
};