This approach uses a stack to efficiently match opening and closing brackets. The stack stores opening brackets, and for each closing bracket encountered, it checks if it closes the last opened bracket (top of the stack).
Time Complexity: O(n), where n is the length of the string, since we process each character once.
Space Complexity: O(n) in the worst case if the string consists only of opening brackets.
1#include <stdbool.h>
2#include <stdio.h>
3#include <string.h>
4
5bool isValid(char * s) {
6 char stack[strlen(s)];
7 int top = -1;
8 for (int i = 0; s[i]; i++) {
9 char c = s[i];
10 if (c == '(' || c == '{' || c == '[') {
11 stack[++top] = c;
12 } else {
13 if (top == -1) return false;
14 char topChar = stack[top--];
15 if ((c == ')' && topChar != '(') ||
16 (c == '}' && topChar != '{') ||
17 (c == ']' && topChar != '['))
18 return false;
19 }
20 }
21 return top == -1;
22}
23
24int main() {
25 printf("%d\n", isValid("()[]{}")); // Output: 1 (true)
26 printf("%d\n", isValid("(]")); // Output: 0 (false)
27 return 0;
28}
This C program uses an array stack to store opening brackets. It checks each character from left to right, pushing opening brackets onto the stack and popping it to match with corresponding closing brackets. If a mismatch is found or the stack isn't empty at the end, it returns false.
This approach uses two pointers with stack-like behavior internally, taking advantage of simple list operations for push and pop.
Time Complexity: O(n)
Space Complexity: O(n/2) = O(n)
1function isValid(s) {
2 if (s.length % 2 !== 0) return false;
3
4 const stack = [];
5 for (let char of s) {
6 if (char === '(' || char === '{' || char === '[') {
7 stack.push(char);
8 } else {
9 if (stack.length === 0) return false;
10 const top = stack.pop();
11 if (!((char === ')' && top === '(') ||
12 (char === '}' && top === '{') ||
13 (char === ']' && top === '['))) {
14 return false;
15 }
16 }
17 }
18 return stack.length === 0;
19}
20
21console.log(isValid("()[]{}")); // Output: true
22console.log(isValid("(]")); // Output: false
The JavaScript implementation checks for an even length initially, then processes each character with a conventional stack dynamics rooted in array handling - verifying the lock-and-key representation of valid parentheses.