[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;
    }
};
posted @ 2016-12-12 16:16  guoyunzhe  阅读(100)  评论(0编辑  收藏  举报