网址:https://leetcode.com/problems/longest-substring-without-repeating-characters/
显然采用sliding window滑动窗口法,辅助以哈希表,判断字符是否已使用
- 不断扩充 j,直到 s[j] 已经使用
- 此时,把 i 移动到 j 之前的 s[j] 字符前面,继续循环
-
class Solution { public: int lengthOfLongestSubstring(string s) { int i = 0, j; int ans = 0; map<char, int> mp; for(j = 0; j<s.size(); j++) { if(mp.find(s[j]) == mp.end() || mp[s[j]] == 0) { mp[s[j]] = 1; } else { ans = max(ans,(j-i)); while(s[i] != s[j]) { mp[s[i]] = 0; i++; } i++; } } ans = max(ans,(j-i)); return ans; } };