LeetCode 20. Valid Parentheses

题目

给定一个字符串所表示的括号序列,包含以下字符: ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, 判定是否是有效的括号序列。

样例
括号必须依照 “()”顺序表示, “()[]{}”是有效的括号,但 “([)]”则是无效的括号。

分析

显然需要用到栈,判断两个是否相匹配,用进站出站判断比较即可

代码

public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        Stack<Character> stack = new Stack<Character>();
        for (Character c : s.toCharArray()) {
        if ("({[".contains(String.valueOf(c))) {
                stack.push(c);
            } else {
               if (!stack.isEmpty() && is_valid(stack.peek(), c)) {
                   stack.pop();
               } else {
                   return false;
               }
           }
       }
       return stack.isEmpty();
    }
    
    private boolean is_valid(char c1, char c2) {
        return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')
            || (c1 == '[' && c2 == ']');
    }
}
public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();
    }
}
    原文作者:六尺帐篷
    原文地址: https://www.jianshu.com/p/938558eadfc7
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞