需要找到由相同字母组成的最长子串的长度。例如,行“aaabbcaaaa”包含四个具有相同字母“aaa”、“bb”、“c”和“aaaa”的子字符串。
我找到了两种方法来做到这一点,但都不太好;
首先,我不在这里检查之前的类似字母sdsffffse
;
因为我只检查当前元素和第二个元素if(line[i] === line[i+1])
。
在第二种方式中,当我尝试检查在该字符串 abababaab
中找到了多少 aa
时,我失败了,但在对象中我添加了所有 a
字母和长度 = 5;
function longRepeat(line) {
let count = {};
let letter = [];
for (let i=0; i<line.length; i++) {
count[line[i]] = i;
if(line[i] === line[i+1]){
letter.push([line[i], line[i+1]])
}
}
/*
second way
for (let x of line) {
count[x] = ~~count[x] + 1;
} */
return letter;
}
console.log(longRepeat('sdsffffse')); f = 4
console.log(longRepeat('ddvvrwwwrggg')); = 3
console.log(longRepeat('abababaab')); // last two a = 2
最佳答案
可能的解决方案:
function longestSubstr(str) {
if (!str) return 0
let maxL = 1
let curL = 1
for (let i = 0; i < str.length - 1; i++) {
let cur = str[i]
let next = str[i + 1]
if (cur === next) {
curL++
} else {
if (maxL < curL) maxL = curL
curL = 1
}
}
if (maxL < curL) maxL = curL
return maxL
}
console.log(longestSubstr("abababaab")) // 2
关于javascript - 如何求最长子串的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52955281/