Valid Parentheses, Leetcode 解题笔记

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.

看完题应该直接反映出使用stack的解法,遇到左括号push,遇到右括号则与stack最上面的配对比较。

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s