压缩字符串
Sunny-117 opened this issue · 5 comments
Sunny-117 commented
压缩字符串
Sunny-117 commented
abbccccaaa->a1b2c4a3
weirong111 commented
function yasuoString(str) {
if (str.length === 0 || str.length === 1) return str;
let cur = str[0];
let count = 1;
let res = "";
for (let i = 1; i < str.length; i++) {
if (str[i] !== cur) {
res += `${cur}${count}`;
cur = str[i];
count = 1;
} else {
count++;
}
}
res += `${cur}${count}`;
return res;
}
bearki99 commented
function ShortenStr(str) {
const stk = [];
let cnt = 0;
let res = "";
for (let i = 0; i < str.length; i++) {
if (stk.length == 0) {
stk.push(str[i]);
cnt++;
}
else if (str[i] === stk[stk.length - 1]) {
cnt++;
} else {
let currentStr = stk.pop();
res += currentStr + cnt;
cnt = 1;
stk.push(str[i]);
}
}
if (stk.length) res += stk.pop() + cnt;
return res;
}
console.log(ShortenStr("abbccccaaa"));
linlai163 commented
function ShortenStr(str) {
const map = new Map();
let res = "";
for (let char of str) {
map.set(char, (map.get(char) || 0) + 1);
}
for ([char, count] of map) {
res += char + count;
}
return res;
}
console.log(ShortenStr("abbccccaaa"));
2239351258 commented
function compressString(str) {
return str.replace(/(.)\1*/g, function(match, p1) {
return p1 + match.length;
});
}