LeetCode-栈-Medium

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步




71. simplify-path 简化路径

解题思路:用/分割字符串
判断每一个字符串是否有效 放入stack中
.不做处理 …如果stack不为空则将最后一个弹出 否则将内容放入stack中

def simplifyPath(path):
    """
    :type path: str
    :rtype: str
    """
    l = path.split("/")
    stack = []
    for i in l:
        if i=="" or i==".":
            continue
        elif i=="..":
            if stack:
                stack.pop()
        else:
            stack.append(i)
            
    res =""
    for i in stack:
        res+="/"+i
    if res=="":
        res = "/"
    return res

94.binary-tree-inorder-traversal 二叉树的中序遍历

解题思路:中序遍历 左根右

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
def inorderTraversal(root):
    """
    :type root: TreeNode
    :rtype: List[int]
    """
    stack=[]
    def traversal(node):
        if node:
            traversal(node.left)
            stack.append(node.val)
            traversal(node.right)
    traversal(root)
    return stack

144.binary-tree-preorder-traversal 二叉树的前序遍历

解题思路:前序遍历 根左右

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
def inorderTraversal(root):
    """
    :type root: TreeNode
    :rtype: List[int]
    """
    stack=[]
    def traversal(node):
        if node:
            stack.append(node.val)
            traversal(node.left)
            traversal(node.right)
    traversal(root)
    return stack

150.evaluate-reverse-polish-notation 逆波兰表达式求值

解题思路:把数值放到stack中 遇到运算符取出末尾两个
不知道为什么int(y/x) 对于负数的时候在自己的机子上是可以的 就是通不过

def evalRPN(tokens):
    """
    :type tokens: List[str]
    :rtype: int
    """
    stack = []
    
    for i in tokens:
        if i=="+":
            x = stack.pop()
            y = stack.pop()
            res = x+y
            print(y,i,x,res)
            stack.append(res)
        elif i=="-":
            x = stack.pop()
            y = stack.pop()
            res = y-x
            print(y,i,x,res)
            stack.append(res)
        elif i=="*":
            x = stack.pop()
            y = stack.pop()
            res = x*y
            print(y,i,x,res)
            stack.append(res)
        elif i=="/":
            x = stack.pop()
            y = stack.pop()
            if x*y<0:
                res = -((-y)//x)
            else:
                res = y//x
            print(y,i,x,res)
            stack.append(res)
        else:
            stack.append(int(i))
    return stack[0]

173.binary-search-tree-iterator 二叉搜索树迭代器

解题思路:左子树及较小数压入stack中,每次取出一个值,将其右子树下的左子树同样压入stack

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class BSTIterator(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.stack =[]
        while root:
            self.stack.append(root)
            root = root.left

    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.stack)>0

    def next(self):
        """
        :rtype: int
        """
        node = self.stack.pop()
        ret = node.val
        node = node.right
        while(node):
            self.stack.append(node)
            node = node.left
        return ret

331.verify-preorder-serialization-of-a-binary-tree 验证二叉树的前序序列化

解题思路:1.计算叶节点个数 添加一个数值必定有两个叶节点(包括#)+2,每一个值也必定是一个叶节点(-1) 最终叶节点剩余值为0
2.将节点压入栈中,根据根左右顺序如果压入的是叶节点必定左右为# 及后面两个为# 则可以将这个叶节点取出用#代替 最终stack中只剩一个#

def isValidSerialization(preorder):
    """
    :type preorder: str
    :rtype: bool
    """
    l = preorder.split(",")
    leaf = 1
    for i in l:
        leaf -=1
        if leaf<0:
            return False
        if i!="#":
            leaf+=2
    return leaf==0
              

def isValidSerialization2(preorder):
        """
        :type preorder: str
        :rtype: bool
        """
        l = preorder.split(",")
        if len(l)>1 and (l[-1]!="#" or l[-2]!="#"):
          return False
        stack =[]
        for i in l:

            stack.append(i)
            if len(stack)<2:
                continue
            while stack[-1]=="#" and stack[-2]=="#":
                if len(stack)==2 or stack[-3]=="#":
                    return False
                stack.pop()
                stack.pop()
                stack.pop()
                stack.append("#")
                if len(stack)==1:
                    break

        if len(stack)==1 and stack[0]=="#":
            return True
        else:
            return False

猜你喜欢

转载自blog.csdn.net/zkt286468541/article/details/85051599