Leetcode #20 Valid Parentheses

Posted by blueskyson on March 28, 2022

Description

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.

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Constraints:

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool isValid(char * s){
    int top = 0;
    char stack[10001];
    memset(stack, '\0', 10001);

    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] == '[' || s[i] == '(' || s[i] == '{') {
            stack[++top] = s[i];
            continue;
        }
        
        if ((s[i] == ']' && stack[top] == '[') ||
            (s[i] == ')' && stack[top] == '(') ||
            (s[i] == '}' && stack[top] == '{')) {
            top--;
            continue;
        }
        return false;
    }

    return (top == 0);
}

Runtime: 0 ms, faster than 100.00% of C online submissions for Valid Parentheses.

Memory Usage: 5.5 MB, less than 78.56% of C online submissions for Valid Parentheses.