查詢 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
- 如果 count 與 0 相同且 temp 的大小 > 0,則
- 在 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))輸入
"(()())()(())"
輸出
['(()())', '()', '(())']
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP