Description
Given a string s 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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 10
4
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.