Comment on A Brutal Look at Balanced Parentheses, Computing Machines, and Pushdown AutomataparentComments−spyrja9moFWIW it's a fairly straightforward algorithm. In C++: bool balanced(const string& text, const string& open, const string& close) { size_t length = text.size(), brackets = open.size(); assert(close.size() == brackets); stack<char> buffer; for (size_t index = 0; index < length; ++index) { char ch = text[index]; for (size_t slot = 0; slot < brackets; ++slot) { if (ch == open[slot]) buffer.push(ch); else if (ch == close[slot]) { if (buffer.empty() || buffer.top() != open[slot]) return false; buffer.pop(); } } } return buffer.empty(); }
Comments
FWIW it's a fairly straightforward algorithm. In C++: