Problem solution · C++

Tag Validator

Tag Validator: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
70 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For Tag Validator, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 70 lines of C++ from the credited upstream file 591.cpp.
  • The implementation keeps its working state in language-native values and containers.
  • 2 loop blocks detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeTag Validator · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  bool isValid(string code) {    if (code[0] != '<' || code.back() != '>')      return false;     stack<string> stack;     for (int i = 0; i < code.length(); ++i) {      int closeIndex = 0;      if (stack.empty() && containsTag)        return false;      if (code[i] == '<') {        // It's inside a tag, so check if it's a cdata.        if (!stack.empty() && code[i + 1] == '!') {          closeIndex = code.find("]]>", i + 2);          if (closeIndex == string::npos ||              !isValidCdata(code.substr(i + 2, closeIndex - i - 2)))            return false;        } else if (code[i + 1] == '/') {  // the end tag          closeIndex = code.find('>', i + 2);          if (closeIndex == string::npos ||              !isValidTagName(stack, code.substr(i + 2, closeIndex - i - 2),                              true))            return false;        } else {  // the start tag          closeIndex = code.find('>', i + 1);          if (closeIndex == string::npos ||              !isValidTagName(stack, code.substr(i + 1, closeIndex - i - 1),                              false))            return false;        }        i = closeIndex;      }    }     return stack.empty() && containsTag;  }  private:  bool containsTag = false;   bool isValidCdata(const string& s) {    return s.find("[CDATA[") == 0;  }   bool isValidTagName(stack<string>& stack, const string& tagName,                      bool isEndTag) {    if (tagName.empty() || tagName.length() > 9)      return false;     for (const char c : tagName)      if (!isupper(c))        return false;     if (isEndTag) {      if (stack.empty())        return false;      if (stack.top() != tagName)        return false;      stack.pop();      return true;    }     containsTag = true;    stack.push(tagName);    return true;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗