Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

leetcode 1249. 移除无效的括号 #31

Open
xxleyi opened this issue Apr 25, 2020 · 0 comments
Open

leetcode 1249. 移除无效的括号 #31

xxleyi opened this issue Apr 25, 2020 · 0 comments
Labels

Comments

@xxleyi
Copy link
Owner

xxleyi commented Apr 25, 2020

题:

给你一个由 '('、')' 和小写字母组成的字符串 s。

你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。

请返回任意一个合法字符串。

有效「括号字符串」应当符合以下 任意一条 要求:

空字符串或只包含小写字母的字符串
可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
 

示例 1:

输入:s = "lee(t(c)o)de)"
输出:"lee(t(c)o)de"
解释:"lee(t(co)de)" , "lee(t(c)ode)" 也是一个可行答案。

示例 2:

输入:s = "a)b(c)d"
输出:"ab(c)d"

示例 3:

输入:s = "))(("
输出:""
解释:空字符串也是有效的

示例 4:

输入:s = "(a(b(c)d)"
输出:"a(b(c)d)"

 

提示:

  1. 1 <= s.length <= 10^5
  2. s[i] 可能是 '('、')' 或英文小写字母

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解:遇到括号匹配问题,要下意识想到「栈」,然后找出需要维护的「循环不变式」,正确初始化相关变量,正确构造循环体,保证循环结束时,循环不变式依然成立,则解题目标应该唾手可得。

此题的「栈思想」其实集中体现在 leftSize 这个变量上。

var minRemoveToMakeValid = function(s) {
  // 初始化「循环不变式」需要的三个变量
  const stack = [], leftIndices = []
  let leftSize = 0

  // 进入循环
  for (let e of s) {
    // 遇到无效右括号直接忽略
    if (leftSize === 0 && e === ')') continue

    // 否则入栈
    stack.push(e)
    // 然后根据当前括号类型正确更新 leftSize 和 leftIndices
    // 以确保「循环不变式」
    if (e === '(') {
      leftSize += 1
      leftIndices.push(stack.length - 1)
    } else if (e === ')'){
      leftSize -= 1
    }
  }

  // 上一个循环终止:进入另一个循环移除无效左括号
  for (let i = 0; i < leftSize; i++) {
    stack[leftIndices[leftIndices.length - 1 - i]] = ''
  }

  // 两个循环终止:位于两侧的无法匹配的括号被删除,正确答案唾手可得
  return stack.join('')
};
@xxleyi xxleyi added the label Apr 25, 2020
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant