JS Likou classic 100 questions - the longest substring without repeated characters

Given a string s, please find the length of the longest substring that does not contain repeated characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: Since the longest substring without repeating characters is "abc", its length is 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: Since the longest substring without repeating characters is "b", its length is 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: Since the longest substring without repeating characters is "wke", its length is 3.
     Note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.

hint:

    0 <= s.length <= 5 * 104
    s consists of English letters, numbers, symbols and spaces

 Pfft... Relying on test case programming, finally got it

 Idea: map stores different substrings, and deletes the map elements in i and index when encountering duplicates. Use an array to store the length of each substring, and finally return the element with the largest tree value in the array

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let i =0
    let arr=[]
    const map = new Map()
    map.set(s[0],0)
    if(s.length == 0){
        return 0
    }
    if(s.length ==1){
        return 1
    }
    let j=1
    while((i<s.length) && (j<s.length)){
        if(!map.has(s[j])){
            map.set(s[j],j)
            j++
        } else {
            let index = map.get(s[j])
            arr.push(j-i)
            for(let k=i; k<=index; k++){
                map.delete(s[k])
            }
            i = index+1
            map.set(s[j],j)
            j++
        }
    }
    arr.push(j-i)
    let max=0
    for(let m=0; m <arr.length; m++) {
        if(arr[m] >max){
            max = arr[m]
        }
    }
    return max
};

Guess you like

Origin blog.csdn.net/qq_36384657/article/details/128172147