[LeetCode] 3. Longest Substring Without Repeating Characters (C++)


Source of subject: https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

Title description

Given a string, you find out which does not contain a repeated character longest substring length.

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

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

示例 3:

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

输入: s = ""
输出: 0
提示:

0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成

General idea

  • Find the longest string that does not contain repeated characters, use a cnt array that records the number of occurrences, through the form of sliding window + double pointer

Sliding window + dual pointer

  • Use an array (or hash table) to count, maintain a variable-length window, and constantly move the left and right pointers to take the longest window length
const int MAXN = 200;
int cnt[MAXN];
class Solution {
    
    
public:
    int lengthOfLongestSubstring(string s) {
    
    
        int ans = 0, len = s.size();
        int left = 0;
        memset(cnt, 0, sizeof(cnt));
        for(int right = 0 ; right < len; ++right){
    
    
            int index = s[right] - 0;
            ++cnt[index];
            while(cnt[index] >= 2){
    
    
                int delIndex = s[left] - 0; 
                --cnt[delIndex];
                ++left;
            }
            ans = max(ans, right - left + 1);
        }
        return ans;
    }
};

Complexity analysis

  • Time complexity: O(n). It can be seen that the left and right pointers have moved n times
  • Space complexity: O(1)

Guess you like

Origin blog.csdn.net/lr_shadow/article/details/113947219
Recommended