程序计算 Python 中需要删除的最少无效括号数,以使字符串正确

pythonserver side programmingprogramming更新于 2026/2/2 15:40:17

假设我们有一串括号;我们必须编写一个函数来计算要删除的最少括号数,以使字符串正确(每个开括号最终都会关闭)。

因此,如果输入为"(()))(",则输出将为 2,因为正确的字符串是"(())",请删除")("。

为了解决这个问题,我们将遵循以下步骤 −

  • total := 0, temp := 0
  • 对于 s 中的每个 p,执行
    • 如果 p 与"("相同,则
      • total := total + 1
    • 否则,当 p 与")"相同且 total 不为 0 时,则
      • total := total - 1
    • 否则,
      • temp := temp + 1
  • 返回 total + temp

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, s):
      total = 0
      temp = 0
      for p in s:
         if p == "(":
            total += 1
         elif p == ")" and total:
            total -= 1
         else:
            temp += 1
      return total + temp
ob1 = Solution()
string = "(()))("
print(ob1.solve(string))

输入

"(()))("

输出

2

相关文章


有用资源