[LeetCode] Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

思路:

用res表示最长不重复字串的长度,left表示滑动窗口的左端,i表示滑动窗口的右端。i-left+1表示滑动窗口的大小

map表示字符c将要出现的left侧。m[c] = 0表示该字符没有重复。m[c] = x表示该字符重复出现且调整的left位置应该处于x处

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int res = 0, left = 0;
        // 用于判断字符c是否重复。若重复其值为left调整的位置。若不重复其值为0
        unordered_map<char, int> m;
        for (int i = 0; i < s.size(); ++i)
        { 
            // 更新窗口left值
            left = max(left, m[s[i]]);
            // 计算重复字符c的位置 
            m[s[i]] = i+1;
            // 更新最大不重复字串长度
            res = max(res, i-left+1);
        }
        return res;
    }
};                

猜你喜欢

转载自www.cnblogs.com/immjc/p/9069627.html