我自己的解法:
难点就在于如何使其计算重复的值,以及最后一次结果别忘记添加进对象里。
function solution(str, index) {
const arr = str.split("");
let currentChar = arr[0];
let time = 1;
const obj = {};
for (let i = 1; i < arr.length; i++) {
if (arr[i] === currentChar) {
time++;
} else {
obj[currentChar] = time;
currentChar = arr[i];
time = 1;
}
}
obj[currentChar] = Math.max(time, obj[currentChar]);
return Object.values(obj)[index - 1];
}
console.log(solution("AAAAHHHBBCDHHHH", 3));
//in: AAAAHHHBBCDHHHHH
// 3
//out:2