zoukankan      html  css  js  c++  java
  • [leetcode]Valid Parentheses @ Python

    原题地址:https://oj.leetcode.com/problems/valid-parentheses/

    题意:

    Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    解题思路:判断括号匹配的合法性。使用一个栈来解决问题。遇到左括号入栈,遇到右括号,检查栈顶的左括号是否匹配,如果匹配,弹栈,如果不匹配,返回错误。如果栈为空,而遇到右括号,同样返回错误。遍历完后,栈如果不空,同样返回错误。

    代码:

    class Solution:
        # @return a boolean
        def isValid(self, s):
            stack = []
            for i in range(len(s)):
                if s[i] == '(' or s[i] == '[' or s[i] == '{':
                    stack.append(s[i])
                if s[i] == ')':
                    if stack == [] or stack.pop() != '(':
                        return False
                if s[i] == ']':
                    if stack == [] or stack.pop() != '[':
                        return False
                if s[i] == '}':
                    if stack == [] or stack.pop() != '{':
                        return False
            if stack:
                return False
            else:
                return True
  • 相关阅读:
    性能学习笔记2-20150129
    Go语言版黑白棋
    Go语言图形界面开发:Go版GTK
    Go入门教程
    本人录制的视频资源(C/C++、Go、Qt、Linux等)
    C++11新特性学习
    protobuf入门教程
    一步步学习Linux多任务编程
    Linux 网络编程系列教程
    一步一步学习GTK+
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3779772.html
Copyright © 2011-2022 走看看