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.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool isValid(string code) {4 if (code[0] != '<' || code.back() != '>')5 return false;6 7 stack<string> stack;8 9 for (int i = 0; i < code.length(); ++i) {10 int closeIndex = 0;11 if (stack.empty() && containsTag)12 return false;13 if (code[i] == '<') {14 15 if (!stack.empty() && code[i + 1] == '!') {16 closeIndex = code.find("]]>", i + 2);17 if (closeIndex == string::npos ||18 !isValidCdata(code.substr(i + 2, closeIndex - i - 2)))19 return false;20 } else if (code[i + 1] == '/') { 21 closeIndex = code.find('>', i + 2);22 if (closeIndex == string::npos ||23 !isValidTagName(stack, code.substr(i + 2, closeIndex - i - 2),24 true))25 return false;26 } else { 27 closeIndex = code.find('>', i + 1);28 if (closeIndex == string::npos ||29 !isValidTagName(stack, code.substr(i + 1, closeIndex - i - 1),30 false))31 return false;32 }33 i = closeIndex;34 }35 }36 37 return stack.empty() && containsTag;38 }39 40 private:41 bool containsTag = false;42 43 bool isValidCdata(const string& s) {44 return s.find("[CDATA[") == 0;45 }46 47 bool isValidTagName(stack<string>& stack, const string& tagName,48 bool isEndTag) {49 if (tagName.empty() || tagName.length() > 9)50 return false;51 52 for (const char c : tagName)53 if (!isupper(c))54 return false;55 56 if (isEndTag) {57 if (stack.empty())58 return false;59 if (stack.top() != tagName)60 return false;61 stack.pop();62 return true;63 }64 65 containsTag = true;66 stack.push(tagName);67 return true;68 }69};70