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.
题意:找出字符串的最长的连续子字符串。
思路:用hash表存存储当前的连续序列,比较序列的长度与length的关系。(wo xiang shuo zhe ge ti hen danteng.)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty())
return 0;
unordered_map<char, int> mymap;
int length = 0;
int tmp = 0;
int j=0;
for (int i = 0; i < s.size(); i++){
char ch = s[i];
if (mymap.insert(pair<char, int>(ch, i)).second){
tmp++;
}
else{
if (tmp > length)
length = tmp;
int t = mymap[ch];
tmp = i - t;
for (j; j<=t; j++){
mymap.erase(s[j]);
}
mymap[ch] = i;
}
}
if (tmp > length)
length = tmp;
return length;
}
};