20. Valid Parentheses

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 stack = new Stack();
        
        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();
        
    }
}

你可能感兴趣的:(20. Valid Parentheses)