top | item 45925574

(no title)

spyrja | 3 months ago

FWIW 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();
  }

discuss

order

No comments yet.