码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Parentheses

时间:2014-10-02 12:40:02      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   java   for   sp   

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

标签:style   blog   color   io   os   ar   java   for   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39735555

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!