zoukankan      html  css  js  c++  java
  • 20. 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.

    链接:http://leetcode.com/problems/valid-parentheses/

    一刷,右半部分的else中的两次判断可以合在一句,但是容易忽略pop,不够直观。

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            parenthese = {
                '(': ')',
                '[': ']',
                '{': '}'
            }
            for char in s:
                if char in parenthese:
                    stack.append(char)
                else:
                    if not stack:
                        return False
                    prev = stack.pop()
                    if parenthese[prev] != char:
                        return False
            return False if stack else True

    2/9/2017, Java

    最后一步一定要判断stack是空的

     1 public class Solution {
     2     public boolean isValid(String s) {
     3         Stack<Character> stk = new Stack<Character>();
     4         char a;
     5         char b;
     6         for (int i = 0; i < s.length(); i++) {
     7             a = s.charAt(i);
     8             if (a == '(' || a == '[' || a == '{') {
     9                 stk.push(a);
    10             } else if (a == ')' || a == ']' || a == '}') {
    11                 if (stk.empty()) return false;
    12                 b = stk.pop();
    13                 if (a == ')' && b == '(' || a == ']' && b == '[' || a == '}' && b == '{') ;
    14                 else return false;
    15             }
    16         }
    17         if (stk.empty()) return true;
    18         return false;
    19     }
    20 }
  • 相关阅读:
    ajax三级联动
    ajax基础
    pdo连接数据
    jquery选择器和基本语句
    会话
    封装连接类
    1218数据访问
    php登陆与注册
    数据库连接和乱码问题
    mysql 严格模式 Strict Mode说明(text 字段不能加默认或者 不能加null值得修改方法)
  • 原文地址:https://www.cnblogs.com/panini/p/5569202.html
Copyright © 2011-2022 走看看