Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

压缩字符串 #124

Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Sunny-117
Copy link
Owner Author

abbccccaaa->a1b2c4a3

@weirong111
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants