假设我们有一个包含平衡括号“(”和“)”的字符串s,我们必须将它们分成最大数量的平衡组。
因此,如果输入类似于“(()())()((())”),则输出将为['(()())','()','(())']
为了解决这个问题,我们将遵循以下步骤-
temp:=空字符串
组:=一个新列表
计数:= 0
对于s中的每个字符b,
数:=数-1
数:=数+ 1
在组末插入temp
temp:=空字符串
如果count与0相同且temp的大小> 0,则
temp:= temp并置b
如果b与'('相同,则
除此以外,
在组末插入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))"(()())()(())"
输出结果
['(()())', '()', '(())']