美文网首页
【Leetcode】3. 无重复字符的最长子串

【Leetcode】3. 无重复字符的最长子串

作者: haha2333 | 来源:发表于2019-09-29 22:15 被阅读0次

javascript版本
思路:滑动窗口思想
当指针向右滑动时,判断前面的字符是否有和现在指针所指的一样。利用str.indexOf()==i(当前指针下标)
如果是则前面的字符串不存在相同的字符。

如果存在相同的,滑动窗口左边就要移到第一个重复字符的右边,继续向右遍历,看遍历指针处字符是否与窗口内字符有重复,有的话,窗口左边继续移到该重复字符处。继续遍历

以下为解题代码
时间复杂度:O(n²)

var lengthOfLongestSubstring = function (s) {
    if (!s.length) return 0
    if (s.length == 1) return 1
    let arr = s.split('')
    let res = 1
    let a = 0 //后重复数字的断位
    for (let i = 1; i < arr.length; i++) {
        let ind = i
        for (let j = a; j < i; j++) {
            if (arr[j] == arr[i]) {  //找到同样的数字
                ind = j
                a = j + 1 //后面继续遍历的起点
            }
        }
        if (ind != i) {
            let temp = i - ind  //遇到相同的先做一个结果
            console.log(i, ind)
            res = res > temp ? res : temp
        } else {
            temp = ind - a + 1
            res = res > temp ? res : temp
        }

    }
    return res
};

是一道想到就容易,想不到就gg的题目
同样的思想,让我想起了两周之前做快手的一道笔试题
求数组中,最长的等差数列??

function getArr(n,arr){
    arr=arr.sort()
    let p=0
    let d=arr[1]-arr[0]
    let temp=[]
    for(let i =1 ;i<arr.length;i++){
        if(arr[i]!=arr[p]+(i-p)*d){//结束等差
            temp.push(i-p)
            p=i-1
            d=arr[i]-arr[i-1]
        }
    }
    let res=0
    for(let i of temp){
        if(i>res) res=i
    }
    return res
}

相关文章

网友评论

      本文标题:【Leetcode】3. 无重复字符的最长子串

      本文链接:https://www.haomeiwen.com/subject/vmihpctx.html