剑指 Offer 48. 最长不含重复字符的子字符串

剑指 Offer 48. 最长不含重复字符的子字符串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

代码

能用 unordered_set 还是用 unordered_set 吧,虽然慢了点。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_set<char> occ;
        int n = s.size();
        int j = 0, ans = 0;
        for (int i = 0; i < n; ++i) {
            while (j < n && !occ.count(s[j])) {
                occ.insert(s[j++]);
            }
            ans = max(ans, j - i);
            occ.erase(s[i]);
        }
        return ans;
    }
};
posted @ 2022-04-28 15:58  沐灵_hh  阅读(18)  评论(0编辑  收藏  举报