LeetCode每日一题:valid parentheses

问题描述

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.

问题分析

括号匹配问题一般都用栈实现。

代码实现

public boolean isValid(String s) {
        if (s.length() == 0) return true;
        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() || (s.charAt(i) == ')' && stack.pop() != '(')
                        || (s.charAt(i) == '}' && stack.pop() != '{')
                        || (s.charAt(i) == ']' && stack.pop() != '[')) {
                    return false;
                }
            }
        }
        if (stack.isEmpty()) return true;
        else return false;
    }

你可能感兴趣的:(LeetCode每日一题:valid parentheses)