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.
記錄每個字母上一次出現(xiàn)的位置,將位置存儲在map中,每次遇到下一個字母便在map中查找這個字母上次遇到的位置筋遭,獲取這段距離,用num記錄最大值并返回桨武。
int lengthOfLongestSubstring(string s) {
if (s.length() == 0) return 0;
map<char, int> mp;
int num = 0;
for (int i = 0, j = 0; i < s.length(); i++) {
map<char, int>::iterator it = mp.find(s[i]);
if (it != mp.end()) {
j = max(j, mp[s[i]] + 1);
}
mp[s[i]] = i;
num = max(num, i - j + 1);
}
return num;
}