Sunny-117/js-challenges

压缩字符串

Sunny-117 opened this issue · 5 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;
  });
}