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 isValid(String s) {
        Stack<Character>stack = new  Stack<Character>();
        String brackets = "({[]})";
        char[] list = s.toCharArray();
        int size = list.length;
        for(int i=0;i<size;i++){
            if(brackets.indexOf(list[i])<=2){
                stack.push(list[i]);
            }
            else{
                if(stack.empty()){
                    return false;
                }
                char top_char = stack.peek();
                int index = 5-brackets.indexOf(top_char);
                if(list[i] == brackets.charAt(index)){
                    stack.pop();
                }
                else{
                    return false;
                }
            }
            
        }
        if(stack.empty()){
            return true;
        }
        else{
            return false;
        }
    }
}

 

posted @ 2015-02-01 13:08  mrpod2g  阅读(120)  评论(0编辑  收藏  举报