[leetcode]_Valid Parentheses

题目:判断给定字符串中的括号是否合法。题目中涉及三种符号'(' + ')' , '[' + ']' , '{' + '}'。

思路:利用stack来存储符号。

   注意申请char型stack是: Stack<Character> op = new Stack<Character>();

     stack.peek() 查看栈顶元素,但是不弹出;stack.pop() 查看栈顶元素,并弹出。 

解题:

public boolean isValid(String s) {
        int len = s.length();
        Stack<Character> op = new Stack<Character>();
        for(int i = 0 ; i < len ; i++){
            char cur = s.charAt(i);
            if(!op.isEmpty()){
                char top = op.peek();
                if(top == '(' && cur == ')' || top == '{' && cur == '}' || top == '[' && cur == ']') op.pop();
                else op.push(cur);
            }else{
                op.push(cur);
            }
        }
        return op.isEmpty();
}

轻松AC,咻~

原文地址:https://www.cnblogs.com/glamourousGirl/p/3732209.html