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.
Solution:
Code:
<span style="font-size:12px;">class Solution {
public:
int lengthOfLongestSubstring(string s) {
int length = s.size();
if (length == 0 || length == 1) return length;
int begin = 0, end = 1;
set<char> hashTable;
int result = 1;
hashTable.insert(s[begin]);
for (; end < length; end++) {
if (hashTable.find(s[end]) == hashTable.end())
hashTable.insert(s[end]);
else {
result = max(result, (int)hashTable.size());
for (; begin < end;) {
if (s[begin] == s[end]) {
begin++;
break;
} else {
hashTable.erase(s[begin]);
begin++;
}
}
}
}
result = max(result, (int)hashTable.size());
return result;
}
};</span>