美文网首页
字符串出现的不重复最长长度(JS)2

字符串出现的不重复最长长度(JS)2

作者: 鐵衣 | 来源:发表于2022-05-10 15:14 被阅读0次
  1. 使用reduce()函数
    注: reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 可以作为一个高阶函数,用于函数的 compose。
    注意: reduce() 对于空数组是不会执行回调函数的。
    语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

function(total,currentValue, index,arr)必需。用于执行每个数组元素的函数。
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。
initialValue 可选。传递给函数的初始值

var lengthOfLongestSubstring = function (s) {
    const arr = [...s]
    let res = 1;
    let result = arr.reduce((total, cur, i, arr) => {
        if (i == 0) {
            return cur;
        } else {
            if (total.indexOf(cur) < 0) {
                return total + cur
            } else if (res < total.length) {
                res = total.length
                return total.slice(total.indexOf(cur) + 1, total.length) + cur
            } else {
                return total.slice(total.indexOf(cur) + 1, total.length) + cur
            }
        }
    }, "")
    if (res < result.length) {
        res = result.length
    }

    return res
};
  1. new Map()
/**
 * 整体思路:
 * 用一个滑动窗口装没有重复的字符,枚举字符记录最大值即可
 * 对于遇到重复字符如何收缩窗口大小?
 * 我们可以用 map 维护字符的索引,遇到相同的字符,把左边界移动过去即可
 * 挪动的过程中记录最大长度
 */
var lengthOfLongestSubstring = function (s) {
    let map = new Map();
    let i = -1
    let res = 0
    let n = s.length
    for (let j = 0; j < n; j++) {
        if (map.has(s[j])) {
            i = Math.max(i, map.get(s[j]))
        }
        res = Math.max(res, j - i)
        map.set(s[j], j)
    }
    return res
};

相关文章

网友评论

      本文标题:字符串出现的不重复最长长度(JS)2

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