[LeetCode_3] Longest Substring Without Repeating Characters

LeetCode: 3. Longest Substring Without Repeating Characters

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int ans = 0, i = 0, j = 0;
        map <char , char> m;
        int n = s.size();
        while (i < n && j < n){
            // 左闭右开
            if(m.find(s[j]) == m.end()){
                // 如果j符合
                m[s[j]] = s[j];
                j +=1;
                ans  = ans > (j - i ) ? ans :(j - i);
            }
            else {
                // 否则窗口缩小,j不前进
                m.erase(s[i]);// 从哈希表中移除
                i +=1;
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/guoyunzhe/p/5845763.html