首页 > 其他 > 详细

LeetCode #20 Valid Parentheses (E)

时间:2015-10-10 00:25:32      阅读:174      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!