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.
思路:一看到连续相关的首先想到滑动窗口,每次为滑动窗口右边增加一个字符,并调整窗口左边,使得窗口里面保持不重复;
调整左边的方法是创建一个哈希表,记录窗口中的字符状态,当右边增加的字符重复时,移动左边窗口直至重复字符的下一个,期间要把经过的非重复字符的哈希表状态置0.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int hash[256] = {0};
int left = 0;
int right = -1;
int maxWidth = 0;
if(s.size() <= 1)
{
return s.size();
}
for(int right=0; right<s.size(); right++)
{
//如果扩展的字符不存在
if(!hash[s[right]])
{
hash[s[right]] = 1;
maxWidth = max(maxWidth, right-left+1);
}
else//如果扩展的字符已经存在,窗口左边移动到该字符的下一个字符
{
while(s[left] != s[right])
{
hash[s[left++]] = 0;
}
left++;
}
}
return maxWidth;
}
};