Longest Substring Without Repeating Characters
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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.size();
if(len <= 1) return len;
vector<bool> chars(256, false);
vector<int> position(256, 0);
int left = 0;
int cur = 0;
int ret = 0;
while(cur < len)
{
char ch = s.at(cur);
if(!chars[ch])
{
chars[ch] = true;
position[ch] = cur;
}
else
{
ret = max(ret, cur - left);
for(int i = left; i < position[ch]; ++i)
chars[s.at(i)] = false;
left = position[ch] + 1;
position[ch] = cur;
}
++cur;
}
return max(ret, cur - left);
}
};