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) {
if (s.empty()) return 0;
char hash[260];
memset(hash,0,sizeof hash);
hash[s[0]] = 1;
int max_len = 1;
size_t len = s.size();
string::iterator iter_first = s.begin();
string::iterator last = s.begin();++last;
for (;last != s.end();)
{
//hash has the s,so we should ++first and modify
//max
if (hash[*last])
{
max_len = std::max(max_len,(int)distance(iter_first,last));
while(*iter_first != *last)
{
hash[*iter_first] = 0;
++iter_first;
}
++iter_first;
}
hash[*last] = 1;
++last;
}
max_len = std::max(max_len,(int)distance(iter_first,last));
return max_len;
}
};