[LeetCode#20]Valid Parentheses

The quesiton:

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.

My analysis:

Pair brackets is a very common usage of stack.
The basic idea is:
1. iff the bracket is a left bracket, we push it onto the stack.
2. iff the bracket is a right bracket, we pop a bracket from the stack, and compare it with the bracket.
Corner cases:
1. "]"
If we pop the stack directly, it would result in an exception.
We should firstly test if the stack is empty, iff empty, the string must be invalid!

2. "[[]"
This case represent the situation, when all right brackets was paired, there are some left brackets remained in the stack.
This case could be detected by test if the final stack is empty. iff not, the string is invalid!

My solution:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> l_stack = new Stack<Character> ();//must box the primitive type before use stack
        char temp;
        
        for (int i = 0; i < s.length(); i++) {
                if (is_left_bracket(s.charAt(i))) {
                    l_stack.push(s.charAt(i));
                } else {
                    if (l_stack.isEmpty()) // if the stack is empty, return false
                        return false;
                        
                    temp = l_stack.pop(); //try to pop an element from a stack would result in exception!
                    if (! is_brackets_match(temp, s.charAt(i))) //check if the two brackts matched!
                        return false; 
                }
        }
        
        if (l_stack.isEmpty()) //test if all left brackets has already been paired 
            return true;
        else 
            return false;
    }
    
    static public boolean is_brackets_match(char b1, char b2) {
        
        if (b1 == '(' && b2 == ')')
            return true; 
        if (b1 == '{' && b2 == '}')
            return true;
        if (b1 == '[' && b2 == ']')
            return true; 
        
        return false;
    }
    
    static public boolean is_left_bracket(char bracket) {
        switch (bracket) {
            case '(' : 
                return true;
            case '{' : 
                return true;
            case '[' : 
                return true;
            default : 
                return false;
        }
    }
}
原文地址:https://www.cnblogs.com/airwindow/p/4193089.html