Created
April 27, 2016 07:23
-
-
Save pravic/df0562efe62af771aa99f95679c8b7f3 to your computer and use it in GitHub Desktop.
Brackets balance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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