题解 | #完成括号匹配#

完成括号匹配

https://www.nowcoder.com/practice/fe8d6a1b88af4ba6b4dbb10972059040

seq = input()
cnt_left = cnt_right = 0
left_add = right_add = 0
for c in seq:
    if c == '[':
        cnt_left += 1
    else:
        cnt_right += 1
    if cnt_right > cnt_left:
        cnt_left = cnt_right = 0
        left_add += 1

cnt_left = cnt_right = 0
for c in seq[::-1]:
    if c == '[':
        cnt_left += 1
    else:
        cnt_right += 1
    if cnt_right < cnt_left:
        cnt_left = cnt_right = 0
        right_add += 1

print('['*left_add + seq + ']'*right_add)

计算不匹配的左括号数量和右括号数量,输出时补上;

括号匹配的过程中,左右括号地位是对称的,所以正向遍历一次,反向遍历一次即可求出不匹配的左右括号数量

全部评论

相关推荐

昨天 13:52
门头沟学院 后端
给🐭🐭个面试机会吧:嘿,mvbatis
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务