Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Aug 8, 2021 · 0 comments
Open

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

frdmu opened this issue Aug 8, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 8, 2021

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

 

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

提示:

  • s.length <= 40000

连续子串,最先想到滑动窗口,难点在于左边界移动到哪里?左边界应该移动到从当前左边界开始出现重复的字符后面。举个例子:

"abcb"
此时left = 0, right = 3, 左边界应该更新为2.

代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> mp;
        int left = 0, n = s.size(), res = 0;
        
        for (int right = 0; right < n; right++) {
            mp[s[right]]++;
            if (mp[s[right]] > 1) {
                res = max(res, right-left);
                int i = left; 
                for (; i < right; i++) {
                    mp[s[i]]--; 
                    if (s[i] == s[right]) {
                        break;        
                    }
                } 
                left = i+1;
            }
        }
        res = max(res, n-left);

        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant