查詢 Python 中的平衡括號組的最大數量的程式


假設我們有一個包含平衡括號“(”和“)”的字串 s,我們必須將它們拆分為最大數量的平衡組。

因此,如果輸入類似於“(()())()(())”,則輸出將為 ['(()())', '()', '(())']

為了解決這個問題,我們將遵循以下步驟 -

  • temp := 空字串
  • groups := 一個新列表
  • count := 0
  • 對 s 中的每個字元 b 執行
    • 如果 count 與 0 相同且 temp 的大小 > 0,則
      • 在 groups 末尾插入 temp
      • temp := 空字串
    • temp := temp 連線 b
    • 如果 b 與 '(' 相同,則
      • count := count + 1
    • 否則,
      • count := count - 1
  • 在 groups 末尾插入 temp
  • 返回 groups

為了更好地理解,讓我們看看以下實現 -

例項

 即時演示

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))

輸入

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

輸出

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

更新於: 06-Oct-2020

388 瀏覽次數

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.