题目地址:
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/
核心的思路是滑动窗口法。
int lengthOfLongestSubstring(string s) {
map<char, int> dic;
int i = -1, res = 0;
for (int j = 0; j < s.size(); j++) {
if (dic.count(s[j])) i = max(i, dic[s[j]]);
dic[s[j]] = j;
res =max(res, j - i);
}
return res;
}
int lengthOfLongestSubstring(string s) {
deque<char> dq;
if (s == "") return 0;
int ans = INT_MIN;
for (auto c : s) {
auto iter = find(dq.begin(), dq.end(), c);
if (iter != dq.end()) dq.erase(dq.begin(), ++iter);
dq.push_back(c);
int len = dq.size();
ans = max(ans, len);
}
return ans;
}