Leetcode 20. Valid Parentheses
Given a string s
containing just the characters '('
, ')'
, '{', '}
, '['
, and ']'
, determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
We can solve this problem using a stack to keep track of opening brackets. Here’s the step-by-step strategy:
'('
, '{'
, '['
), push it onto the stack.')'
, '}'
, ']'
), check the stack:
false
.true
(all open brackets were matched); otherwise, return false
.#include <iostream>
#include <stack>
#include <unordered_map>
bool isValid(std::string s) {
std::stack<char> stack;
std::unordered_map<char, char> matchingBrackets = {
{')', '('},
{'}', '{'},
{']', '['}
};
for(char c : s) {
if(matchingBrackets.count(c)) {
if(stack.empty() || stack.top() != matchingBrackets[c]) {
return false;
}
stack.pop();
} else {
stack.push(c);
}
}
return stack.empty();
}
int main() {
std::string s = "()[]{}"; // Change the string according to your test case
if(isValid(s)) {
std::cout << "The string is valid." << std::endl;
} else {
std::cout << "The string is not valid." << std::endl;
}
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?