用 Python 编写程序,查找括号中最大数量的平衡组

pythonserver side programmingprogramming更新于 2026/1/12 5:00:17

假设我们有一个字符串 s,其中包含平衡的括号"("和")",我们必须将它们拆分成最大数量的平衡组。

因此,如果输入为"(()())()(())",则输出为 ['(()())', '()', '(())']

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

  • temp := 空白字符串
  • groups := a new list
  • count := 0
  • 对于 s 中的每个字符 b,执行
    • 如果 count 与 0 相同且 size temp > 0,则
      • 在组末尾插入 temp
      • temp := 空字符串
    • temp := temp 连接 b
    • 如果 b 与 '(' 相同,则
      • count := count + 1
    • 否则,
      • count := count - 1
  • 在组末尾插入 temp
  • 返回组

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

示例

class Solution:
   def solve(self, s):
      temp = ''
      groups = []
      count = 0
      for b in s:
         if count == 0 and len(temp) > 0:
            groups.append(temp)
         temp = ''
         temp += b
         if b == '(':
            count += 1
         else:
            count -= 1
      groups.append(temp)
      return groups
s = "(()())()(())"
ob = Solution()
print(ob.solve(s))

输入

"(()())()(())"

输出

['(()())', '()', '(())']

相关文章


有用资源