当前位置:网站首页>Leetcode: Sword finger offer 48 The longest substring without repeated characters

Leetcode: Sword finger offer 48 The longest substring without repeated characters

2022-07-06 08:51:00 Bertil

Please find the longest substring in the string that does not contain duplicate characters , Calculate the length of the longest substring .

Example 1:

 Input : "abcabcbb"
 Output : 3 
 explain :  Because the longest substring without repeating characters is  "abc", So its length is  3.

Example 2:

 Input : "bbbbb"
 Output : 1
 explain :  Because the longest substring without repeating characters is  "b", So its length is  1.

Example 3:

 Input : "pwwkew"
 Output : 3
 explain :  Because the longest substring without repeating characters is  "wke", So its length is  3.
      Please note that , Your answer must be   Substring   The length of ,"pwke"  Is a subsequence , Not substring .

Tips :

  • s.length <= 40000

Be careful : This topic and the main station 3 The question is the same :https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/


Their thinking

1. First define the left pointer , Create a new one map To store each character and its index value
2. Then traverse the right pointer , If the character has appeared , Then the left pointer moves to the right
3. Finally, according to the position of the left and right pointers, the maximum value of the substring without repeated characters is constantly taken

Code

/** * @param {string} s * @return {number} */
var lengthOfLongestSubstring = function(s) {
    
    let l = 0
    let res = 0
    const map = new Map()
    for(let r = 0; r < s.length; r++) {
    
        if(map.has(s[r]) && map.get(s[r]) >= l) {
    
            l = map.get(s[r]) + 1
        }
        res = Math.max(res, r - l + 1)
        map.set(s[r],r)
    }
    return res
};
原网站

版权声明
本文为[Bertil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060844309000.html