Valid Parentheses

来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 06:51

Question:

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.



//********** Hints ************

运用Stack即可

//*****************************


Solution:

public class Solution {
    public boolean isValid(String s) {
        
        if(s.length() == 0)
            return true;
        
        LinkedList<Character> stack = new LinkedList<Character>();
        
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            
            switch(c){
                case '(':
                    stack.add(c);
                    break;
                case ')':
                    if(stack.isEmpty())
                        return false;
                    if(!stack.removeLast().equals('('))
                        return false;
                    break;
                case '[':
                    stack.add(c);
                    break;
                case ']':
                    if(stack.isEmpty())
                        return false;
                    if(!stack.removeLast().equals('['))
                        return false;
                    break;
                case '{':
                    stack.add(c);
                    break;
                case '}':
                    if(stack.isEmpty())
                        return false;
                    if(!stack.removeLast().equals('{'))
                        return false;
                    break;
                default:
                    return false;
            }
        }
        if(stack.isEmpty())
            return true;
        return false;
    }
}

0 0
原创粉丝点击