Skip to content

Instantly share code, notes, and snippets.

@residentkrm
Created May 4, 2016 21:37
Show Gist options
  • Save residentkrm/9b0ce8ce698e5fa71e7f5acae81c2ced to your computer and use it in GitHub Desktop.
Save residentkrm/9b0ce8ce698e5fa71e7f5acae81c2ced to your computer and use it in GitHub Desktop.
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <string>
#include <stack>
bool isOpenBracket(char symbol) {
return symbol == '(' || symbol == '{' || symbol == '[';
}
bool isClosingBracket(char symbol) {
return symbol == ')' || symbol == '}' || symbol == ']';
}
char getOpenBracketPair(char bracket) {
return (bracket == '}') ? '{' : (bracket == ')') ? '(' :
(bracket == ']') ? '[' : '\0';
}
bool areParenthesesGood(const std::string &source) {
std::stack<char> stack;
for (size_t i = 0; i < source.size(); ++i) {
if (isOpenBracket(source[i])) {
stack.push(source[i]);
}
else {
if (isClosingBracket(source[i])) {
char openBracket = getOpenBracketPair(source[i]);
if (!stack.empty() && stack.top() == openBracket) {
stack.pop();
}
else {
return false;
}
}
}
}
if (!stack.empty())
std::cout << "unexpected " << stack.top() << std::endl;
return stack.empty();
}
int main(int argc, char *argv[])
{
srand(time(0));
std::string expression = "{{((x+(g-[f+h]*c)-(q+w)))}}";
std::cout << areParenthesesGood(expression) << std::endl;
std::cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment