连续最多的字符
题目
给一个字符串,找出连续最多的字符,以及次数。
例如字符串 'aabbcccddeeee11223' 连续最多的是 e ,4 次。
传统方式
嵌套循环,找出每个字符的连续次数,并记录比较。
时间复杂度看似是 O(n^2),因为是嵌套循环。 但实际上它的时间复杂度是 O(n),因为循环中有跳转。
双指针
画图解释,参考视频讲解。
只有一次循环,时间复杂度是 O(n)
性能测试,发现两者时间消耗一样,循环次数也一样。
/**
* 求连续最多的字符和次数(嵌套循环)
* @param str str
*/
function findContinuousChar1(str) {
const res = {
char: '',
length: 0,
};
const length = str.length;
if (length === 0) return res;
let tempLen = 0; //记录临时长度
for (let i = 0; i < length; i++) {
tempLen = 0;
const s1 = str[i];
for (let j = i; j < length; j++) {
const s2 = str[j];
if (s1 === s2) {
tempLen++;
}
if (s1 !== s2 || j === length - 1) {
if (tempLen > res.length) {
res.char = s1;
res.length = tempLen;
}
if (i < length - 1) {
i = j - 1;
}
break;
}
}
}
return res;
}
/**
* 求连续最多的字符和次数(双指针)
* @param str str
*/
function findContinuousChar2(str) {
const res = {
char: '',
length: 0,
};
const length = str.length;
if (length === 0) return res;
let tempLen = 0; //记录临时长度
let i = 0;
let j = 0;
for (; i < length; i++) {
const s1 = str[i];
const s2 = str[j];
if (s1 === s2) {
tempLen++;
}
if (s1 !== s2 || i === length - 1) {
if (tempLen > res.length) {
res.char = s2;
res.length = tempLen;
}
tempLen = 0;
if (i < length - 1) {
j = i;
i--;
}
}
}
return res;
}