LeetCode #3 简单题

题目: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

题解: i j 分别记录目标字符串的左右边界。对当前字符 x,如果前面出现过,则更新左边界为上次出现位置的下一个,然后更新当前字符 x 的位置,遍历过程中记录一下 j - i + 1的最大值就好了。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int ans = 0;
        int len = s.size();
        std::map<int, int> pos;
        for (int i = 0, j = 0; j < len; ++j){
            if (pos.find(s[j]) != pos.end()){
                int left = pos[s[j]];
                i = left > i ? left : i;
            }
            ans = (j - i + 1) > ans ? (j - i + 1) : ans;
            pos[s[j]] = j + 1;
        }
        return ans;
    }
};

猜你喜欢

转载自www.cnblogs.com/error408/p/11546510.html