20. Valid Parentheses 有效的括号(栈)

101 阅读1分钟

Given a string s 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.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1

Input: s = "()"
Output: true

Example 2

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

Example 3

Input: s = "(]"
Output: false

Constraints

  • 1 <= s.length <= 10e4
  • s consists of parentheses only '()[]{}'.

Solution

  • 首先应该特判,如果括号个数为奇数个显然无法匹配
  • 进行模拟出入栈操作,当前字符能够和栈顶匹配,共同出栈,否则入栈。
bool isValid(char * s){
    int n = strlen(s);
    if (n % 2) return false;
    char stack[10000];
    int top = 1;
    stack[0] = s[0];
    for (int i = 1; i < n; i++) {
        if (!top) stack[top++] = s[i];
        else if (stack[top - 1] == '(' && s[i] == ')') top--;
        else if (stack[top - 1] == '[' && s[i] == ']') top--;
        else if (stack[top - 1] == '{' && s[i] == '}') top--;
        else stack[top++] = s[i];
    }
    return !top;
}

题目链接:20. 有效的括号 - 力扣(LeetCode)