力扣刷题 数据结构和算法(五)

一、栈(Stack)

 

访问 Access :O(1)  栈顶元素

 搜索 Search :O(N)

 插入 Insert :O(1)

 删除 Remove :O(1)  栈顶元素

二、Python 栈的常用操作:

1、创建栈

2、添加元素

 

3、获取栈顶元素

 

4、删除栈顶元素

 

5、 栈的大小

6、栈是否为空

 

 7、栈的遍历(边删除边遍历)

三、力扣20题 

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) == 0:
            return True
        stack = []
        for c in s:
            if c == '(' or c == '[' or c == '{':
                stack.append(c)
            else:
                if len(stack) == 0:
                    return False
                else:
                    temp = stack.pop()
                    if c == ')':
                        if temp != '(':
                            return False
                    elif c == ']':
                        if temp != '[':
                            return False
                    elif c == '}':
                        if temp != '{':
                            return False
        return True if len(stack) == 0 else False

 四、力扣496题

class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        stack = []
        for num in nums2:
            stack.append(num)
        for num in nums1:
            temp = []
            isFound = False
            max = -1
            while(len(stack) != 0 and not isFound):
                top = stack.pop()
                if top > num:
                    max = top
                elif top == num:
                    isFound = True
                temp.append(top)
            res.append(max)
            while len(temp) != 0:
                stack.append(temp.pop())
        return res

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值