JavaScript算法系列--无连续重复字符的最长子串

mac2025-10-23  7

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

示例 1:

输入: "abcabcbb" 输出: 7 解释: 因为无连续重复字符的最长子串是 "abcabcb",所以其长度为 7。

示例 2:

输入: "bbbbb" 输出: 1 解释: 因为无连续重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "sdfffffsdee" 输出: 4 解释: 因为无连续重复字符的最长子串是 "fsde",所以其长度为 4。

话不多说,上code:

var lengthOfNopersistenceStr = function (s) { if (typeof s === 'string' && s !== '') { s = s.replace(/(\w)(?:\1+)/g, function () { return arguments[1] + ' ' + arguments[1] }) const arr = s.split(' ') const nums = [] for (const item of arr) { nums.push(item.length) } return Math.max(...nums) } return 0 }

 

最新回复(0)