- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 52 lines of Python from the credited upstream file 591.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 def isValid(self, code: str) -> bool:3 if code[0] != '<' or code[-1] != '>':4 return False5 6 containsTag = False7 stack = []8 9 def isValidCdata(s: str) -> bool:10 return s.find('[CDATA[') == 011 12 def isValidTagName(tagName: str, isEndTag: bool) -> bool:13 nonlocal containsTag14 if not tagName or len(tagName) > 9:15 return False16 if any(not c.isupper() for c in tagName):17 return False18 19 if isEndTag:20 return stack and stack.pop() == tagName21 22 containsTag = True23 stack.append(tagName)24 return True25 26 i = 027 while i < len(code):28 if not stack and containsTag:29 return False30 if code[i] == '<':31 32 if stack and code[i + 1] == '!':33 closeIndex = code.find(']]>', i + 2)34 if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]):35 return False36 elif code[i + 1] == '/': 37 closeIndex = code.find('>', i + 2)38 if closeIndex == -1 or not isValidTagName(39 code[i + 2: closeIndex],40 True):41 return False42 else: 43 closeIndex = code.find('>', i + 1)44 if closeIndex == -1 or not isValidTagName(45 code[i + 1: closeIndex],46 False):47 return False48 i = closeIndex49 i += 150 51 return not stack and containsTag52