-
-
Notifications
You must be signed in to change notification settings - Fork 232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
压缩字符串 #124
Comments
abbccccaaa->a1b2c4a3 |
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;
} |
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")); |
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")); |
function compressString(str) {
return str.replace(/(.)\1*/g, function(match, p1) {
return p1 + match.length;
});
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: