题解 | #合法的括号字符串#

合法的括号字符串

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return bool布尔型
#
class Solution:
    def isValidString(self , s: str) -> bool:
        # write code here
        left = []
        star =[]
        s = s[1:-1]
        # 把所有(和*当左边界压入栈
        for i in range(len(s)):
            if s[i] == '(':
                left.append(i)
            elif s[i] == '*':
                star.append(i)
            else:
                # )右括号出栈
                if len(left):
                    left.pop()
                elif len(star):
                    star.pop()
                # 右括号不够匹配了,返回false
                else:
                    return "false"
        # 然后右括号匹配
        while len(left) and len(star):
            if len(left)>len(star):
                return "false"
            if left.pop() > star.pop():
                return "false"
        return "true"
        

print(Solution().isValidString(input()))

#Java求职#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务