每日一题之LeetCode 栈简单题集合496,682,232,225,155,844,20

496 下一个最大的元素
方法1 :自己瞎写的 没有考虑到栈的特性
class Solution:
def nextGreaterElement(self, nums1, nums2):

     L=[]
    for i in nums1:
         k=nums2.index(i)
         lenth2=len(nums2)
        if k==lenth2-1:
           L.append(-1)
         for j in range(k+1,lenth2):
             if nums2[j]>i:
                 L.append(nums2[j])
                 break

             if j==lenth2-1:
                 L.append(-1)
    return L  

方法2:网上大神写的 很膜拜
class Solution:
def nextGreaterElement(self, nums1, nums2):

                    d = {}
                    st = []
                    ans = []

                    for x in nums2:
                        while len(st) and st[-1] < x:
                            d[st.pop()] = x
                        st.append(x)

                    for x in nums1:
                        ans.append(d.get(x, -1))

                    return ans

682.棒球比赛
注:好久前写的,后面再吧栈的写出来
ops= ["35","-32","C","39","+","-48","C","5","88","-52","+","C","D","D","100","C","+","-74","53","59"]
L=[]
sum=[]
lenth=len(ops)
for i in range(0,lenth):
if i==0:
sum.append(int(ops[i]))
else:

   if ops[i]==‘C‘:

            sum.insert(0,0)

            sum.insert(1,0)

            sum.pop()

   elif  ops[i]==‘D‘:
    sum.append(sum[i-1]*2)

   elif ops[i]==‘+‘:
    sum.append(sum[i-1]+sum[i-2])
   else :

        sum.append(int(ops[i]))

score=0
for j in sum:
score=score+j
print(score)
232.用栈实现队列
方法1:网上的,用两个list来实现
class MyQueue:

def __init__(self):
    """
    Initialize your data structure here.
    """
    self.stact=[]
    self.queue=[]
    self.len=0

def push(self, x):
    """
    Push element x to the back of queue.
    :type x: int
    :rtype: void
    """
    self.stact.append(x)
    self.len=self.len+1

def pop(self):
    """
    Removes the element from in front of queue and returns that element.
    :rtype: int
    """

    while len(self.stact)!=0:
        self.queue.append(self.stact.pop())

    x = self.queue.pop()

    while len(self.queue)!= 0:
       self.stact.append(self.queue.pop())

    self.len -=1
    return x

def peek(self):
    """
    Get the front element.
    :rtype: int
    """

    while len(self.stact)!=0:
        self.queue.append(self.stact.pop())

    x = self.queue.pop()
    self.queue.append(x)
    while len(self.queue)!= 0:
       self.stact.append(self.queue.pop())

    return x

def empty(self):
    """
    Returns whether the queue is empty.
    :rtype: bool
    """

    if self.len==0:
        return False

方法2:用一个list来实现,比较简单
class MyQueue:

def __init__(self):
    """
    Initialize your data structure here.
    """
    self.queue = []

def push(self, x):
    """
    Push element x to the back of queue.
    :type x: int
    :rtype: void
    """
    self.queue.append(x)

def pop(self):
    """
    Removes the element from in front of queue and returns that element.
    :rtype: int
    """
    if len(self.queue)>0:
       print( self.queue.pop(0))

def peek(self):
    """
    Get the front element.
    :rtype: int
    """
    if len(self.queue)>0:
        print( self.queue[0])

def empty(self):
    """
    Returns whether the queue is empty.
    :rtype: bool
    """
    if len(self.queue)>0:
        return False
    else:
        return True
def shuchu(self):
     for i in self.queue:
         print(i)

235,用队列来实现栈
注:与上面异曲同工
class MyStack:

def __init__(self):
    """
    Initialize your data structure here.
    """
    self.queue = []

def push(self, x):
    """
    Push element x to the back of queue.
    :type x: int
    :rtype: void
    """
    self.queue.append(x)

def pop(self):
    """
    Removes the element from in front of queue and returns that element.
    :rtype: int
    """
    if len(self.queue)>0:
        return self.queue.pop()
        #len(self.queue)-=1

def top(self):
    """
    Get the front element.
    :rtype: int
    """
    if len(self.queue)>0:
        return self.queue[-1]

def empty(self):
    """
    Returns whether the queue is empty.
    :rtype: bool
    """
    if len(self.queue)>0:
        return False
    else:
        return True

155,最小栈
注:可以使用深复制在里面找出来最小值,但会超时,很慢很慢
方法1:用min 函数,较慢,因为每次都执行
class MinStack:

def __init__(self):
    """
    initialize your data structure here.
    """
    self.queue = []
    self.min=None
def push(self, x):
    """
    :type x: int
    :rtype: void
    """
    self.queue.append(x)
    self.min=min(self.queue)

def pop(self):
    """
    :rtype: void
    """
    if len(self.queue)>0:
       self.queue.pop()
       self.min=min(self.queue)
       return self.queue
def top(self):
    """
    :rtype: int
    """
    if len(self.queue)>0:
        return self.queue[-1]

def getMin(self):
    """
    :rtype: int
    """
    return self.min

方法2:判断,比较快
class MinStack(object):
def init(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = None

def push(self, x):
    """
    :type x: int
    :rtype: void
    """
    self.stack.append(x)
    if self.min == None or self.min > x:
        self.min = x

def pop(self):
    """
    :rtype: void
    """

    popItem = self.stack.pop()
    if len(self.stack) == 0:
        self.min = None
        return popItem

    if popItem == self.min:
        self.min = self.stack[0]
        for i in self.stack:
            if i < self.min:
                self.min = i
    return popItem

def top(self):
    """
    :rtype: int
    """
    return self.stack[-1]

def getMin(self):
    """
    :rtype: int
    """
    return self.min

844.比较含退格的字符串
注:注意遇到‘#’时,字符串长度为0时的处理,以及两个“#”,字符串长度为0时的处理。PS,这是老子自己写出来运行最快的代码了,代码也简洁,写了半个小时吧,有一丢丢自豪。还学会了在类里调用函数。一个类里不能函数调用函数。
class Solution:

def backspaceCompare(self, S, T):
    """
    :type S: str
    :type T: str
    :rtype: bool
    """

    S1=back(S)
    T1=back(T)
    if S1==T1:
        return True
    else:
        return False

def back(L):
K=[]
for i in L:
if i==‘#‘ and len(K)!=0:

               K.pop()
        elif  i==‘#‘ and len(K)==0:
               pass
        else:
            K.append(i)
    return K

20,有效的括号
注:好久前写的了,也是在学栈之前写的,后面把栈的写出来。
class Solution:
def isValid(self, s):

    a=list(s)
    b=[]                            #存放左括号的栈  qc:list当做栈
    c={‘(‘:‘)‘,‘[‘:‘]‘,‘{‘:‘}‘}     #字典存储     qc;key:value 键:值
    for i in a:
        if i==‘‘:
            return True
        elif i in c: #如果是字典中的键,即左括号,放进栈
            b.append(i)
        else:
            if len(b)==0: #先判断是否有左括号存在
                return False
            else:
                 #字典得到该键的值==栈顶值对应的右括号
                if c.get(b[-1])!=i:
                    return False
                else:
                    del b[-1]      #删除栈顶元素
    if len(b)!=0:  #若还存在左括号,此时已没有右括号,出错
        return False
    return True

PS.写这么一些题还是有用的,至少遇到一些题知道其实是采用了栈的思想,以前都是瞎写。编程还是要有思维。

原文地址:http://blog.51cto.com/13930723/2327301

时间: 2024-07-30 09:17:28

每日一题之LeetCode 栈简单题集合496,682,232,225,155,844,20的相关文章

LeetCode #1 简单题

题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 题解:简单题,没啥可说的,不想 n2 复杂度搞,map存一下logn吧先 1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 std::map<int, int> numMap; 5 vector<int>

【bzoj2751】[HAOI2012]容易题(easy) 数论,简单题

Description 为了使得大家高兴,小Q特意出个自认为的简单题(easy)来满足大家,这道简单题是描述如下:有一个数列A已知对于所有的A[i]都是1~n的自然数,并且知道对于一些A[i]不能取哪些值,我们定义一个数列的积为该数列所有元素的乘积,要求你求出所有可能的数列的积的和 mod 1000000007的值,是不是很简单呢?呵呵! Input 第一行三个整数n,m,k分别表示数列元素的取值范围,数列元素个数,以及已知的限制条数.接下来k行,每行两个正整数x,y表示A[x]的值不能是y.

LeetCode #6 简单题(小模拟)

题目: 将一个给定字符串根据给定的行数,以从上往下.从左到右进行 Z 字形排列.然后横向输出.LeetCode上有几个样例可以看看. 题解:模拟一下就好了- -,对原字符串s排列完后,横向每个添加到ans中去就行了 class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; int len = (int)s.size(), gridSize = numRows * 2 -

leetCode #2 简单题

题目:给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储一位数字.如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和.您可以假设除了数字 0 之外,这两个数都不会以 0 开头. 题解:就指向两个链表的头的指针依次向后遍历.算和的余数,记录一下进位.如果L1先遍历到末尾的话,就把L1最后一个指针指向L2当前的next,即把L2剩余的部分接在L1的结尾.这样可以节省不少开辟新Node的空间,然后继续用进位和L1当前N

LeetCode #3 简单题

题目: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 题解: i j 分别记录目标字符串的左右边界.对当前字符 x,如果前面出现过,则更新左边界为上次出现位置的下一个,然后更新当前字符 x 的位置,遍历过程中记录一下 j - i + 1的最大值就好了. class Solution { public: int lengthOfLongestSubstring(string s) { int ans = 0; int len = s.size(); std::map<int,

LeetCode #5 简单题

题目:求最长回文子串 题解:manacher算法,百度一堆讲解- -,我也不说了,想知道啥的自己百度去吧 class Solution { public: string longestPalindrome(string s) { string manaStr = "$#"; for (int i=0;i<s.size();i++){ manaStr += s[i]; manaStr += '#'; } vector<int> rd(manaStr.size(), 0)

LeetCode #7 简单题(反转整数)

题目:翻转整数  123 -> 321,-123 -> -321 题解: long long 存一下好了,注意溢出返回0就行了 class Solution { public: int reverse(int x) { long long orix = x; long long rev = 0; bool isLess0 = orix < 0; orix = orix < 0 ? -1 * orix : orix; while(orix != 0){ rev = rev * 10

50题(ACM学习推荐题)

POJ推荐50题 1. 标记"难"和"稍难"的题目可以看看,思考一下,不做要求,当然有能力的同学可以直接切掉. 2. 标记为 A and B 的题目是比较相似的题目,建议大家两个一起做,可以对比总结,且二者算作一个题目. 3. 列表中大约有70个题目.大家选做其中的50道,且每类题目有最低数量限制. 4. 这里不少题目在 BUPT ACM FTP 上面都有代码,请大家合理利用资源. 5. 50个题目要求每个题目都要写总结,养成良好的习惯. 9. 这个列表的目的在于让

Leetcode动态规划【简单题】

目录 Leetcode动态规划[简单题] 53. 最大子序和 题目描述 思路分析 复杂度分析 70.爬楼梯 题目描述 思路分析 复杂度分析 121.买卖股票的最佳时机 题目描述 思路分析 复杂度分析 303.区域和检索-数组不可变 题目描述 思路分析 复杂度分析 Leetcode动态规划[简单题] 动态规划(Dynamic programming,简称DP),是一种把原问题分解为相对简单的子问题的方式求解复杂问题的方法.动态规划相较于递归,拥有更少的计算量. 53. 最大子序和 题目描述 给定一