C++ Nesting
#include <string>
#include <vector>
int nesting(const std::string& s)
{
if (s.empty()) {
return 1;
}
std::vector<char> stack;
for (char c : s) {
if (c == ')') {
if (stack.empty() || stack.back() != '(') {
return 0;
}
stack.pop_back();
} else {
stack.push_back(c);
}
}
return stack.empty() ? 1 : 0;
}
This treats the string like a balance counter: open parentheses add one, closing ones remove one.