1370.上升下降字符串
链接:1370.上升下降字符串
难度:Easy
标签:哈希表、字符串、计数
简介:给你一个字符串 s ,请你根据下面的算法重新构造字符串,请你返回将 s 中字符重新排序后的 结果字符串 。
题解 1 - typescript
- 编辑时间:2020-11-25
- 执行用时:124ms
- 内存消耗:45.1MB
- 编程语言:typescript
- 解法介绍:利用 while 进行永动。
function sortString(s: string): string {
  let len = s.length;
  const cache: Record<string, number> = {};
  const setCache = (c: string) => {
    cache[c] = 1 + (cache[c] ? cache[c] : 0);
  };
  for (const c of s) setCache(c);
  const arr = Object.entries(cache).sort(([c1], [c2]) => c1.codePointAt(0)! - c2.codePointAt(0)!);
  let i = -1;
  let ans = '';
  const compute = () => {
    ans += arr[i][0];
    arr[i][1]--;
    len--;
  };
  while (len !== 0) {
    while (len !== 0) {
      i++;
      if (i === arr.length) break;
      if (arr[i][1] === 0) continue;
      compute();
    }
    while (len !== 0) {
      i--;
      if (i === -1) break;
      if (arr[i][1] === 0) continue;
      compute();
    }
  }
  return ans;
}