刷leetcode-整理字符串 | 刷题打卡

97 阅读1分钟

一、题目描述:

原题地址

leetcode1544

二、思路分析:

这几天都在刷栈,这个典型的栈思维。

  • 遇到自己的同类大小写出栈
  • 其他,进栈

三、AC 代码:

var makeGood = function(s) {
const arr = s.split("");
const res = [];
for (let i = 0; i < arr.length; i++) {
  const cur = arr[i];
  if (res.length === 0) {
    res.push(cur);
    continue;
  }
  const stackTop = res[res.length - 1];
  const isUpper =
    cur === String.fromCharCode(stackTop.charCodeAt() - 32);
  const isLower =
    cur === String.fromCharCode(stackTop.charCodeAt() + 32);
  if (isUpper || isLower) {
    res.pop();
    continue;
  }
  res.push(arr[i]);
}
return res.join("");
};

四、总结:

  • 遇到将最后一个扔出去的情景,想想栈