Valid Parentheses

来源:互联网 发布:冒险岛boss数据 编辑:程序博客网 时间:2024/05/16 20:29

Q:

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.


Solution:

public class Solution {    public boolean isValid(String s) {        Stack<Character> stack = new Stack<Character>();        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if (c == '(' || c == '[' || c == '{') {                stack.push(c);                continue;            }            if (stack.isEmpty())                return false;            if (c == ')' && stack.peek() == '(')                stack.pop();            else if (c == ']' && stack.peek() == '[')                stack.pop();            else if (c == '}' && stack.peek() == '{')                stack.pop();        }        if (stack.isEmpty())            return true;        return false;    }}


0 0