首页 > 代码库 > Valid Parentheses

Valid Parentheses

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 class Solution {
    public boolean match(char a,char b)
    {
        String s="(){}[]";
        String p=""+a+b;
        return s.indexOf(p)>=0;
    }
    public boolean isValid(String s) {
        if(s==null||s.length()==0||((s.length()&1)>0))
        {
            return false;
        }
        Stack<Character> stack=new Stack<Character>();
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);
            stack.push(c);
            while(stack.size()>1)
            {
                char a=stack.pop();
                char b=stack.pop();
                if(!match(b,a))
                {
                    stack.push(b);
                    stack.push(a);
                    break;
                }
            }
        }
        return stack.empty();
    }
}


Valid Parentheses