用 Python 编写程序来查找最长平衡子序列的长度
pythonserver side programmingprogramming更新于 2026/1/19 8:12:17
假设我们有一个字符串 s,其中包含括号"("和")",我们必须找到平衡括号的最长子序列的长度。
因此,如果输入为 s = "())(()(" ,则输出将为 4,因为我们可以取子序列"()()"
要解决这个问题,我们将遵循以下步骤 −
res := 0
n := size of s
close := 0
对于 i 在 n - 1 到 0 的范围内,减少 1,执行
如果 s[i] 与 ")" 相同,则
close := close + 1
否则,
如果 close > 0,则
close := close - 1
res := res + 2
返回 res
让我们看看下面的实现以便更好地理解 −
示例
class Solution:
def solve(self, s):
res = 0
n = len(s)
close = 0
for i in range(n - 1, -1, -1):
if s[i] == ")":
close += 1
else:
if close > 0:
close -= 1
res += 2
return res
ob = Solution()
s = "())(()("
print(ob.solve(s))
输入
"())(()("
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

