码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #20 Valid Parentheses (E)

时间:2015-10-10 00:27:18      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

[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();
    }
}

 

LeetCode #20 Valid Parentheses (E)

标签:

原文地址:http://www.cnblogs.com/zhangqieyi/p/4865539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!