无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

const lengthOfLongestSubstring = (s) => {
    const length = s.length
    if(length < 2) return length
    let res = 0
    for(let i = 0; i <length - 1; i++){
        const set = new Set()
        set.add(s[i])
        let j = i + 1;
        while(j < length && !set.has(s[j])){
            set.add(s[j])
            j++
        }
        if(set.size > res){
            res = set.size
        }
    }
    return res
}

优化

const lengthOfLongestSubstringByDoublePointer = (s = "pwwkew") => {
    const length = s.length
    let res = 0
    const arr = []
    let fastIndex = -1
    for(let i = 0; i < length; i++){
        arr.shift()
        while(fastIndex + 1 < length && !arr.includes(s[fastIndex + 1])){
            arr.push(s[fastIndex + 1])
            fastIndex++
        }
        res = Math.max(res, fastIndex + 1 - i)
    }
    return res
}

Leecode提交通过

posted @ 2020-06-18 14:32  671_MrSix  阅读(187)  评论(0编辑  收藏  举报