题解 | #完成括号匹配#

完成括号匹配

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)

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

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

全部评论

相关推荐

12-18 19:36
已编辑
门头沟学院 Java
程序员牛肉:可以的,简历没毛病了。 虽然还是偏向同质化,不过学历不错。后续我觉得重心放到刷实习+摆脱同质化问题上
实习简历求拷打
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务