有效括号 Valid Parentheses

题目

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

以下为详细说明:

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

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

思路&题解

class Solution {
   public boolean isValid(String s) {
        if (s.isEmpty()) {
            return true;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if (c == ')' && top == '(') {
                    continue;
                }
                if (c == '}' && top == '{') {
                    continue;
                }
                if (c == ']' && top == '[') {
                    continue;
                }
                return false;
            }
        }
        return stack.isEmpty();
    }
}

知识点分析

powered by Gitbook最近更新 2019-03-13

results matching ""

    No results matching ""