LeetCode #20 Valid Parentheses (E)

[Problem]

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.

 

[Analysis]

思路上属于利用data structure的特性。利用Stack FIFO的特性可以大大简化这道题。

 

[Solution]

import java.util.Stack;

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i< s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(')');
            } else if (c == '[') {
                stack.push(']');
            } else if(c == '{') {
                stack.push('}');
            } else {
                if (stack.size() == 0 || c != stack.pop()) {
                    return false;
                } 
            }
        }
        
        return stack.empty();
    }
}

 

posted on 2015-10-09 23:52  张惬意  阅读(135)  评论(0编辑  收藏  举报