栈与队列20|1047|150

20有效的括号

class Solution:
    def isValid(self, s: str) -> bool:
        s_list = list(s)
        if len(s_list) % 2 != 0:
            return False
        stack = []
        for item in s_list:
            if item == "(":
                stack.append(")")
            elif item == "[":
                stack.append("]")
            elif item == "{":
                stack.append("}")
            elif item == ")" or item == "]" or item == "}":
                if len(stack) == 0 or stack[-1] != item:
                    return False
                elif stack[-1] == item:
                    stack.pop()
        if len(stack) == 0:
            return True
        elif len(stack) != 0:
            return False

1047删除字符串中的所有相邻重复项

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        s_list = list(s)
        result = ""
        for item in s_list:
            if len(stack) == 0 or stack[-1] != item:
                stack.append(item)
            elif stack[-1] == item:
                stack.pop()
        for item in stack:
            result += item
        return result

150逆波兰表达式求值

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for item in tokens:
            if item in {"+", "-", "*", "/"}:
                num2 = stack.pop()
                num1 = stack.pop()
                if item == "+":
                    val = num1 + num2
                elif item == "-":
                    val = num1 - num2
                    
                elif item == "*":
                    val = num1 * num2
                elif item == "/":
                    val = num1 // num2
                    if val < 0 and num1 % num2 != 0:
                        val += 1
                stack.append(val)
            else:
                stack.append(int(item))
        return stack.pop()

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 14:45
bg是二本双一流硕,目标是Java后端开发岗,投暑期实习0大厂面试,只有极少的大厂测开,可能投的晚加上简历太烂加上0实习?求大佬们给个建议
程序员小白条:别去小厂,初创或者外包,尽量去中小,100-499和500-999,专门做互联网产品的,有公司自研的平台和封装的工具等等,去学习一些业务相关的,比如抽奖,积分兑换,SSO认证,风控,零售等等,目标 Java 后端开发吗?你要不考虑直接走大厂测开?如果技术不行的话,有面试你也很难过的
实习,不懂就问
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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