leetcode解题方案--020--Valid Parentheses

来源:互联网 发布:c语言什么时候用flag 编辑:程序博客网 时间:2024/06/05 22:31

题目

检查括号合法性
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.

分析

设置一个栈,遇到左括号入栈,遇到右括号和栈顶元素比较,一致就出栈,结束时查看栈是否为空

 public static boolean isValid(String s) {        Stack<Character> aa = new Stack<>();        char [] ss = s.toCharArray();        for (int i = 0; i<ss.length;i++) {            switch (ss[i]) {                case '{':                    aa.push('}');                    break;                case '[':                    aa.push(']');                    break;                case '(':                    aa.push(')');                    break;                default:                    if (aa.empty()) return false;                    char xxx = aa.peek();                    if (xxx!=ss[i]) {                        return false;                    } else {                        aa.pop();                    }            }        }        return aa.empty();    }