LeetCode 20. Valid Parentheses

来源:互联网 发布:迅捷聊天记录恢复软件 编辑:程序博客网 时间:2024/05/18 02:14

原题:(频率5)

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.


题意:就是判断括号是否对称



代码和思路

很简单,用一个栈,碰到open括号,就把close括号加入栈。遇到close括号,就弹出栈顶元素,看是否相等。


class Solution {    public boolean isValid(String s) {        Stack<Character> stack = new Stack<>();        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();    }}



原创粉丝点击