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

合法的括号字符串

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return bool布尔型
#
class Solution:
    
    def isValidString(self , s: str) -> bool:
        # write code here
        stk = []
        star_stk = []
        for index, ch in enumerate(s):
            if ch == "(":
                stk.append((index, ch))

            elif ch == ")":
                if stk and stk[-1][1] == "(":
                    stk.pop()
                elif len(star_stk) > 0:
                    star_stk.pop()
                else:
                    return False
            elif ch == "*":
                star_stk.append((index, ch))

        print(f"stk:{stk}\nstar_stk:{star_stk}")
		
		# 这里需要判断 "*"出现在"("后才合法.
        while len(stk) > 0 and len(star_stk) > 0:
            left = stk.pop()
            star = star_stk.pop()
            if star[0] < left[0]:
                return False

        if len(stk) == 0:
            return True

        return False

全部评论

相关推荐

轻絵梨花泪沾衣:南泵,大少爷驾到通通闪开
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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