题目连接:Leetcode 003 Longest Substring Without Repeating Characters
解题思路:用一个map来记录每个字符出现的位置,一个变量记录不重复子串的起始位置。然后遍历字字符串,如果当前字符没有出现过,就插入一条记录在map中;如果字符出现过,就要将当前不重复子串的起始位置 到 重复字符出现的位置(map中记录)之间的字符在map中删除,并且更新不重复子串的起始位置。遍历过程中维护子串的最大长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int begin = 0, ans = 0;
map<char, int> g;
for (int i = 0; i < s.size(); i++) {
while (g.count(s[i])) {
g.erase(s[begin++]);
}
g[s[i]] = i;
ans = max(ans, i - begin + 1);
}
return ans;
}
};