Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 10, 2020 19:29
Show Gist options
  • Save misterpoloy/f24db8f74f88bd0ef3e64e811106cfc7 to your computer and use it in GitHub Desktop.
Save misterpoloy/f24db8f74f88bd0ef3e64e811106cfc7 to your computer and use it in GitHub Desktop.
Check for balanced parentheses using stack = () true ([)] false
// https://www.youtube.com/watch?v=QZOLb0xHB_Q&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=18
#include <iostream>
#include <stack>
#include <string>
bool testBalance(std::string str) {
std::stack<char> expressions;
for (int i = 0; i < str.size(); i++) {
char current = str[i];
if (current == '{' || current == '[' || current == '(') {
expressions.push(current);
continue;
}
if (current == '}' || current == ']' || current == ')') {
if (expressions.empty()) {
return false;
} else {
// Compare the match
char last = expressions.top();
bool congruent = false;
switch (last) {
case '{':
if (current == '}')
congruent = true;
break;
case '[':
if (current == ']')
congruent = true;
break;
case '(':
if (current == ')')
congruent = true;
break;
default:
break;
}
if (congruent) {
expressions.pop();
} else {
return false;
}
}
}
}
return expressions.empty();
};
int main() {
std::string str;
getline(std::cin, str);
std::cout << testBalance(str) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment