#591
Tag Validator
HardStringStackStackString Parsing
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to efficiently manage open tags and validate nested structures in a single pass through the string. This reduces unnecessary checks and allows for quick validation of tags.
⚙️
Algorithm
6 steps- 1Step 1: Initialize an empty stack and a pointer to traverse the string.
- 2Step 2: While traversing, check for '<' to identify tags.
- 3Step 3: For each start tag, validate the tag name and push it onto the stack.
- 4Step 4: For each end tag, check if it matches the top of the stack and pop if valid.
- 5Step 5: Handle CDATA sections by skipping over them without pushing to the stack.
- 6Step 6: After processing, ensure the stack is empty for valid tag structure.
solution.py27 lines
1def isValid(code):
2 stack = []
3 i = 0
4 while i < len(code):
5 if code[i:i+9] == '<![CDATA[':
6 i = code.find(']]>', i) + 3
7 if i == 2:
8 return False
9 elif code[i] == '<':
10 j = code.find('>', i)
11 if j == -1:
12 return False
13 tag = code[i:j+1]
14 if tag.startswith('</'):
15 tag_name = tag[2:-1]
16 if not stack or stack[-1] != tag_name:
17 return False
18 stack.pop()
19 else:
20 tag_name = tag[1:-1]
21 if not (1 <= len(tag_name) <= 9) or not tag_name.isupper():
22 return False
23 stack.append(tag_name)
24 i = j + 1
25 else:
26 i += 1
27 return len(stack) == 0ℹ
Complexity note: The complexity is O(n) because we make a single pass through the string, processing each character once, and the stack can grow with the number of open tags.
- 1Using a stack is crucial for managing nested structures effectively.
- 2Validating tag names and ensuring they follow the rules is essential for correctness.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.