Sponsored
Sponsored
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 <stack>
2#include <string>
3
4bool isValid(std::string s) {
5 std::stack<char> stack;
6 for (char& c : s) {
7 if (c == '(' || c == '{' || c == '[') {
8 stack.push(c);
9 } else {
10 if (stack.empty()) return false;
11 char top = stack.top();
12 stack.pop();
13 if ((c == ')' && top != '(') ||
14 (c == '}' && top != '{') ||
15 (c == ']' && top != '['))
16 return false;
17 }
18 }
19 return stack.empty();
20}In C++, we utilize the STL stack to handle opening brackets. It pushes each found opening bracket and checks them against closing ones as they appear. The program efficiently manages balance checking through stack operations.
This C solution strategically checks potential stack overflow and underflow using an array pointer technique, relying on an indexing control within the allowed stack-size limits. Each mismatched pair check ensures parentheses are properly closed.