def cheak_kuohao(s):
    stack = []
    for char in s:
        if char in {'(','[','{'}:
            stack.append(char)
        elif char == ')':
            if len(stack)>0 and stack[-1] == '(':
                stack.pop()
            else:
                return False
        elif char == ']':
            if len(stack) > 0 and stack[-1] == '[':
                stack.pop()

        elif char == '}':
            if len(stack) > 0 and stack[-1] == '{':
                stack.pop()
            else:
                return False

    if len(stack) == 0:
        return True
    else:
        return False

print(cheak_kuohao('()[[{]]}'))


感觉拿栈的思想去验证左右括号太二了,改变下顺序 从栈顶出去就不靠谱了

栈做迷宫还是比较靠谱的

maze = [
    [1,1,1,1,1,1,1,1,1,1],
    [1,0,0,1,0,0,0,1,0,1],
    [1,0,0,1,0,0,0,1,0,1],
    [1,0,0,0,0,1,1,0,0,1],
    [1,0,1,1,1,0,0,0,0,1],
    [1,0,0,0,1,0,0,0,0,1],
    [1,0,1,0,0,0,1,0,0,1],
    [1,0,1,1,1,0,1,1,0,1],
    [1,1,0,0,0,0,0,1,0,1],
    [1,1,1,1,1,1,1,1,1,1]
]


dirs = [lambda x, y: (x + 1, y),
        lambda x, y: (x - 1, y),
        lambda x, y: (x, y - 1),
        lambda x, y: (x, y + 1)]


def mpath(x1, y1, x2, y2):
    stack = []
    stack.append((x1, y1))
    while len(stack) > 0:
        curNode = stack[-1]
        if curNode[0] == x2 and curNode[1] == y2:
            #到达终点
            for p in stack:
                print(p)
            return True
        for dir in dirs:
            nextNode = dir(curNode[0], curNode[1])
            if maze[nextNode[0]][nextNode[1]] == 0:
                #找到了下一个路径
                stack.append(nextNode)
                #标记为已经走过,防止死循环
                maze[nextNode[0]][nextNode[1]] = 1
                break
        else: #四个方向都找不到
            maze[curNode[0]][curNode[1]] = -1 #死路
            stack.pop() #回溯

    print("没有路")
    return False

mpath(1,1,8,8)
posted @ 2017-10-27 14:40  点||点  阅读(121)  评论(0编辑  收藏  举报