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.
Subscribe to see which companies asked this question.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int length = 0;
int start = -1;
unordered_map<char, int> cmap;//记录字符串s中的字符以及位置
unordered_map<char, int>::iterator map_iter;
for(int i = 0; i!=s.length();++i)
{
map_iter=cmap.find(s[i]);//遍历字符串s,在cmap中寻找字符s[i]
if(map_iter!=cmap.end())//遍历过程中出现重复字符时,将当前字符的位置更新为子字符串长度的计算起点,计算子字符串的长度
{
if(map_iter->second>start) start = map_iter->second;
cmap.erase(map_iter);
}//if
cmap.insert(make_pair(s[i],i));
length = max(length,i - start);//更新子字符串长度
}//for
return length;
}
};