LeetCode 20 Valid Parentheses (栈)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/89601571

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

题目链接:https://leetcode.com/problems/valid-parentheses/

题目分析:栈模拟

class Solution {
    public boolean isValid(String s) {
        int top = 0;
        int[] stk = new int[s.length() + 1];
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '[' || ch == '{') {
                stk[++top] = ch;
            } else if (ch == ')' && top > 0 && stk[top] == '(') {
                top--;
            } else if (ch == ']' && top > 0 && stk[top] == '[') {
                top--;
            } else if (ch == '}' && top > 0 && stk[top] == '{') {
                top--;
            } else {
                return false;
            }
        }
        return top == 0;
    }
}

猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/89601571