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

【leetcode 】20. Valid Parentheses

时间:2016-04-09 21:51:04      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

这题需要注意:

  1. 栈的空指针
  2. 全局变量stack需要clear
  3. 输入结束时栈长度不为空

 

 

public class Solution {
    private static final Stack<Character> stack = new Stack<Character>();
    
    public boolean isValid(String s) {
        stack.clear();
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (!isLeft(c)) {
                if (stack.isEmpty()) {
                    return false;
                }
                if (!isPair(stack.pop(), c)) {
                    return false;
                }
            } else {
                stack.push(c);
            }
        }
        return stack.isEmpty();
    }
    
    private boolean isLeft(char c) {
        return c == ‘(‘ || c == ‘[‘ || c == ‘{‘;
    }
    
    private boolean isPair(char left, char right) {
        if (left == ‘(‘) {
            return right == ‘)‘;
        } else if (left == ‘[‘) {
            return right == ‘]‘;
        } else {
            return right == ‘}‘;
        }
    }
}

 

【leetcode 】20. Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/lanhj/p/5372713.html

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