003 Longest Substring Without Repeating Characters

看到这题,本来想用字符串做来着,不过一时之间忘了字符串中的indexOf函数了,倒是想起了字符串转数组的函数split(尴尬),于是就转为数组了。
后来看了题解后换成字符串检索,果然快了10ms左右。

思路其实挺简单,就是遍历一次字符串,然后检测这个字符在之前出现过没有,没有的话就加在后边,
有的话就先计算之前的字符串长度与max比较,然后删除出现的字符及之前的字符串,
接着把新来的字符放入temp后边。最后在比较一次字符串长度就结束。

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {

    // let temp = []
    // let max=0
    // s.split('').map((d)=>{
    //     let index=temp.indexOf(d)
    //     if(index!=-1)
    //     {
    //         temp.length>max && (max=temp.length)
    //         temp.splice(0,index+1)
    //     }
    //     temp.push(d)
    // })
    // temp.length>max &&(max=temp.length)
    // return max
    let temp=''
    let max=0
    for(n of s)
    {
        let index=temp.indexOf(n)
        if(index!=-1)
        {
            temp.length>max && (max=temp.length)
            temp = temp.slice(index+1)
        }
        temp+=n
    }
    temp.length>max &&(max=temp.length)
    return max
};

猜你喜欢

转载自www.cnblogs.com/selfdef/p/12650929.html