1. 程式人生 > >LeetCode-棧-Easy

LeetCode-棧-Easy

記錄了初步解題思路 以及本地實現程式碼;並不一定為最優 也希望大家能一起探討 一起進步


目錄



20. valid-parentheses 有效的括號

解題思路:將左邊的括號放入棧中 彈出時檢查是否一致

def isValid(s):
    """
    :type s: str
    :rtype: bool
    """
    #'(', ')', '{', '}', '[' and ']'
    if len(s) % 2 != 0:
            return False
    l =[]
    left =['(','{','[']
    for i in s:
        if i in
left: l.append(i) else: if len(l)==0: return False if i==')' and len(l)>0 and l.pop()!='(': return False if i=='}' and len(l)>0 and l.pop()!='{': return False if i==']' and len(l)>
0 and l.pop()!='[': return False return l==[]

155.min-stack 最小棧

解題思路:

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.min = []
        

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        if not self.min or x<=self.min[-1]:
            self.min.append(x)
        

    def pop(self):
        """
        :rtype: void
        """
        v = self.stack.pop()
        if self.min and v == self.min[-1]:
            self.min.pop()
        

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

    def getMin(self):
        """
        :rtype: int
        """
        if len(self.min)>0:
            return self.min[-1]

225.implement-stack-using-queues 用佇列實現棧

解題思路:

class MyStack(object):

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

    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        

    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        return self.stack.pop()
        

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

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        return len(self.stack)==0

232.implement-queue-using-stacks 用棧實現佇列

解題思路:

class MyQueue(object):

    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
        """
        return self.queue.pop(0)
        

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        return self.queue[0]
        

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return len(self.queue)==0

496.next-greater-element-i 下一個更大元素 I

解題思路:

def nextGreaterElement(findNums, nums):
    """
    :type findNums: List[int]
    :type nums: List[int]
    :rtype: List[int]
    """
    def find(n,l):
        ret = -1
        for i in l:
            if i >n:
                ret = i
                return ret
        return ret
    ret =[]
    for i in findNums:
        pos = nums.index(i)
        ans = find(i,nums[pos+1:])
        ret.append(ans)
    return ret

682.baseball-game 棒球比賽

解題思路:建立一個list用來儲存有效分值

def calPoints(ops):
    """
    :type ops: List[str]
    :rtype: int
    """
    l=[]
    sum = 0
    for i in ops:
        if i=="+":
            v = l[-1]+l[-2]
            l.append(v)
            sum+=v
        elif i=="D":
            v = 2* l[-1]
            l.append(v)
            sum+=v
        elif i=="C":
            v = l.pop()
            sum-=v
        else:
            sum += int(i)
            l.append(int(i))
        print(sum,l)
    return sum

844.backspace-string-compare 比較含退格的字串

解題思路:

def backspaceCompare(S, T):
    """
    :type S: str
    :type T: str
    :rtype: bool
    """
    rs=[]
    rt=[]
    for i in S:
        if i=="#":
            if rs:
                rs.pop()
        else:
            rs.append(i)
    for i in T:
        if i=="#":
            if rt:
                rt.pop()
        else:
            rt.append(i)
    print(rs,rt)
    return rs==rt