Google/LinkCode:E-有效的括号序列

来源:互联网 发布:周末网络国债理财申请 编辑:程序博客网 时间:2024/06/06 14:17

题目


题目来源:Link


给定一个字符串所表示的括号序列,包含以下字符: '(', ')''{''}''[' 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                if(s==null || s.length()==0) return true;                Stack<Character> stack = new Stack<Character>();        //Stack<Character> s2 = new Stack<Character>();                for(int i=0; i<s.length(); i++){            char tmp = s.charAt(i);            if(stack.isEmpty()){                if(tmp==')' || tmp==']' || tmp=='}')                    return false;                stack.add(tmp);            }else{                char peek = stack.peek();                if(tmp=='(' || tmp=='[' || tmp=='{'){                    stack.add(tmp);                }else{                    if(tmp==')' && peek!='(')                        return false;                    if(tmp==']' && peek!='[')                        return false;                    if(tmp=='}' && peek!='{')                        return false;                    stack.pop();                }            }        }        if(stack.isEmpty())            return true;        else            return false;    }}