1249.移除无效的括号
链接:1249.移除无效的括号
难度:Medium
标签:栈、字符串
简介:给你一个由 '('、')' 和小写字母组成的字符串 s。你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。请返回任意一个合法字符串。
题解 1 - typescript
- 编辑时间:2021-03-19
- 执行用时:112ms
- 内存消耗:45.3MB
- 编程语言:typescript
- 解法介绍:从左到右去除右括号,从右到左去除左括号。
function minRemoveToMakeValid(s: string): string {
  let fCount = 0;
  let ans = '';
  for (const c of s) {
    if (c === '(') {
      fCount++;
      ans += c;
    } else if (c === ')') {
      if (fCount !== 0) {
        ans += c;
        fCount--;
      }
    } else {
      ans += c;
    }
  }
  const temp = ans;
  fCount = 0;
  ans = '';
  for (let i = temp.length - 1; i >= 0; i--) {
    const c = temp[i];
    if (c === ')') {
      fCount++;
      ans = c + ans;
    } else if (c === '(') {
      if (fCount !== 0) {
        ans = c + ans;
        fCount--;
      }
    } else {
      ans = c + ans;
    }
  }
  return ans;
}