面試常見算法題

1、SingleLinkList python

    1.1 鏈表反轉app

    1.2 鏈表相鄰兩個節點交換blog

    1.3 判斷鏈表是否是有環隊列

 

2、Stackelement

    2.1判斷輸入的括號是否合法字符串

         

 def isValid(self, s: str) -> bool:
        stack = []
        str_dic = {')':'(', ']':'[', '}':'{'}
        
        for i in s:
            if i not in str_dic:
                stack.append(i)
            else:
                if not stack:
                    return False
                else:
                    res = stack.pop()
                    if str_dic[i] == res:
                        pass
                    else:
                        return False
        return not stack
整個題目的思考邏輯是, 若是輸入的字符串是又括號 ,判斷咱們的stack是否爲空,若是是空的直接報錯,若是不是空的,則要彈出棧頂元素,而後根據咱們的字典,以輸入的字符爲k,拿到value,判斷value與咱們的棧頂元素是否一致,若是不一致,直接報錯。
若是是輸入的是左擴展,咱們直接壓入棧,最後將整個字符串遍歷完成後,判端棧中是否還有元素,若是有說有部分沒有匹配上,報錯。

  

  2.2 只經過棧實現一個隊列 input

class MyQueue:

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

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.input.append(x)
        

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if len(self.output):
            return self.output.pop()    
        for j in range(len(self.input)):
            self.output.append(self.input.pop())
        return self.output.pop()    
            
        

    def peek(self) -> int:
        """
        Get the front element.
        """
        if not len(self.output):
           
            for j in range(len(self.input)):
                self.output.append(self.input.pop())
            return self.output[-1]
        else:
             return self.output[-1]
        

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if len(self.output) or len(self.input):
            return False
        return True這個問題一個思路是,經過兩個棧,來實現先進先出, 過程是,A棧只用來push就是壓入,另一個棧,當peek或者pop時,將A棧的數據,,放入到B棧中,而後在從B棧中進行返回,這樣就達到了一個先進先出的結果
相關文章
相關標籤/搜索