Task is to check if given string contains balanced sets of {}
, []
and ()
.
For example, check(\"{[}]\")
must return
Checking for nested braces seems like a natural case for std::stack
. Push braces onto the stack as you iterate over the input and test for correct matches when you see a closing brace.
bool check(const std::string &expression) // balanced and nested?
{
std::stack stack;
for (auto ch : expression) {
switch (ch) {
case '(': // open parenthesis
case '<': // open angle
case '[': // open bracket
case '{': // open brace
stack.push(ch);
break;
case ')': // close parenthesis
if (stack.empty() || stack.top() != '(') return false;
stack.pop();
break;
case '>': // close angle
if (stack.empty() || stack.top() != '<') return false;
stack.pop();
break;
case ']': // close bracket
if (stack.empty() || stack.top() != '[') return false;
stack.pop();
break;
case '}': // close brace
if (stack.empty() || stack.top() != '{') return false;
stack.pop();
break;
}
}
return stack.empty(); // no unmatched braces left?
}