20. Valid Parentheses

2016-10-17  本文已影响0人  MoveOnLC

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

用一个stack解决问题,从头到尾扫描一下,遇到左括号压栈,遇到右括号就将stack的top元素和其配对弹出。如果中间遇到问题不能配对,或者到最后stack不空,就返回false。

public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        if (s.length() == 0) {
            return false;
        }
        
        Stack<Character> stack = new Stack<Character>();
        
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[' ) {
                stack.push(s.charAt(i));
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                 else if ((s.charAt(i) == ')' && stack.peek() == '(') 
                || (s.charAt(i) == ']' && stack.peek() == '[')
                || (s.charAt(i) == '}' && stack.peek() == '{')) {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        
        return stack.isEmpty();
        
    }
}
上一篇下一篇

猜你喜欢

热点阅读