<script>
//取出字符串,判断重复停止,添加到新字符串中
function solution(str) {
if(typeof str !== "string"){//类型不为字符串返回空
return '';
}
if (str.length <= 1){//直接返回源字符串
return str;
}
let newStr = '';
let s = str.charAt(0);
let num = 1; //跳过第一个
let total = str.length;
for (let i = 1; i < total; i++) {
let nowS = str.charAt(i);
if (nowS === s) {
num = num + 1; // 增加数量
if (i + 1 === total) {
newStr += `${s}${num}`; // 遍历结束时,拼接最后的字符串
}
} else {
newStr += `${s}${num}`; // 拼接字符串
num = 1; // 重置为1
s = nowS; // 转为下一个字符s
}
}
if (newStr.length >= str.length) {// 生成的字符串长度大于等于源字符串 返回源字符串 否则返回生成的字符串
return str;
} else {
return newStr;
}
};
console.log(
'输出:',
solution('aabcccccaaa'), // a2b1c5a3
solution('aabbcc'), // aabbcc
solution('aaaa'), // a4
solution('a'), // a
solution('') // ''
);