查找 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))
输入
"(()())()(())"
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
['(()())', '()', '(())']
广告