Skip to content

Instantly share code, notes, and snippets.

@pravic
Created April 27, 2016 07:23
Show Gist options
  • Save pravic/df0562efe62af771aa99f95679c8b7f3 to your computer and use it in GitHub Desktop.
Save pravic/df0562efe62af771aa99f95679c8b7f3 to your computer and use it in GitHub Desktop.
Brackets balance
#include <vector>
int verify(const char* input) {
std::vector<char> stack;
while(const char c = *input++) {
if (c == '(' || c == '[' || c == '<') {
stack.push_back(c);
} else if (c == ')' || c == ']' || c == '>') {
if (stack.empty()) { return 0; }
char& prev = stack.back();
bool valid = true;
if (prev == '(') valid &= c == ')';
if (prev == '[') valid &= c == ']';
if (prev == '<') valid &= c == '>';
if (valid) {
stack.pop_back();
} else {
return 0;
}
}
}
return stack.empty();
}
#include <consoleapp.hxx>
#include <cassert>
int ntl::consoleapp::main()
{
assert(1, verify("a(b)"));
assert(1, verify("[<>]"));
assert(0, verify("[(]"));
assert(0, verify("[(])"));
assert(0, verify("><"));
assert(1, verify("z([<>-()]<a>)"));
assert(1, verify(""));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment