算法练习4-最长无重复子串


//-------------------字符串所有子串 - 递归---------------------------
var strFromSubStr = function (str) {
    let result = []
    
    function dfs (s) {
        if (s.length === 1) {
            result.push(s)
            return result
        }
        let one = s[0]
        let subs = dfs(s.slice(1))
        subs.forEach(ss => {
            result.push(one, one + ss)
        })
        return result
     }
    dfs(str)
    return [...new Set(result)]
}

 

// ------------------最长无重复子串----------------------------
var lengthOfLongestSubstring = function(s) {
    let max = 0
    let left = 0
    let right = 1
    let l = 0
    let r = 0
    if (s.length === 0 || s.length === 1) return s.length
    while (right < s.length) {
        let sub = s.slice(left, right)
        if (sub.indexOf(s[right]) > -1) {
            left++
            continue
        } else {
            right++
        }
        if (right - left > max) {
            max = right - left
            l = left
            r = right
        }
    }
    console.log(s.slice(l, r))
    return s.slice(l, r).length
};

 

posted @ 2022-07-28 13:19  monkey-K  阅读(20)  评论(0编辑  收藏  举报