Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2193 from su5kk/patch-1
Browse files Browse the repository at this point in the history
Update 0020-valid-parentheses.cpp
  • Loading branch information
tahsintunan authored Feb 1, 2023
2 parents e196f53 + f70f5a7 commit 5bc1a36
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions cpp/0020-valid-parentheses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,29 @@ class Solution {
public:
bool isValid(string s) {
stack<char> open;
unordered_map<char, char> parens = {
{')', '('},
{']', '['},
{'}', '{'},
};

for (int i = 0; i < s.size(); i++) {
if (s[i] == ')' || s[i] == '}' || s[i] == ']') {
for (const auto& c : s) {
if (parens.find(c) != parens.end()) {
// if input starts with a closing bracket.
if (open.empty()) {
return false;
}
if (s[i] == ')' && open.top() != '(') {
return false;
}
if (s[i] == '}' && open.top() != '{') {
return false;
}
if (s[i] == ']' && open.top() != '[') {

if (open.top() != parens[c]) {
return false;
}

open.pop();
} else {
open.push(s[i]);
open.push(c);
}
}

if (!open.empty()) {
return false;
}
return true;
return open.empty();
}
};

0 comments on commit 5bc1a36

Please sign in to comment.