You are given a string code. Return true if it is a valid snippet under these rules, false otherwise.
A tag is a start tag <NAME>, some content, and an end tag </NAME> with the same name. A name is valid when it is 1 to 9 capital letters. The whole code must be exactly one valid tag: nothing may come before or after it.
Inside a tag the content may hold plain text, other valid tags (properly nested), and CDATA sections: <![CDATA[, any characters, then the first ]]>. Whatever is inside CDATA is plain text, even if it looks like a tag. Every other < starts a tag, whose name is everything up to the next >; if there is no >, or the name is invalid, or the tags do not match up, the code is invalid.
Example 1
Input: code = "<A>hi<B><![CDATA[</A>]]></B></A>" Output: true Why: the </A> inside CDATA is just text; B closes, then A
2 more examples and the constraints
Example 2
Input: code = "<X><Y></X></Y>" Output: false Why: Y is still open when X tries to close
Example 3
Input: code = "<TOOLONGNAME>x</TOOLONGNAME>" Output: false Why: a name may have at most 9 letters
Constraints
- 1 ≤ length of code ≤ 500
- code holds English letters, digits, spaces and the characters < > / ! [ ] .
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collapse innermost tagsO(n²)
- One scan with a stackO(n)
The idea in one sentence
Side by side
| Approach | Time | Relative work for 500 characters, deeply nested | Verdict |
|---|---|---|---|
| Collapse innermost tags | O(n²) | Short; fine at this size | |
| One scan with a stack | O(n) | Best; one pass, no regex |
n = length of code.
Edge cases to test
- Text outside the tag.
<A></A>xor a leading space: the whole code must be one tag. - Two tags side by side.
<A></A><B></B>is invalid: there must be one outer tag. - CDATA outside any tag.
<![CDATA[x]]><A></A>is invalid. - Stray `<` in the text.
<A>1 < 2</A>fails: the<swallows text up to the next>as a name. - Name length. 9 capital letters is fine; 10, zero or any lowercase letter is not.
Common mistakes
- Allowing text or a second tag after the outer tag has closed.
- Checking for a plain
<before<![CDATA[, so CDATA is parsed as a tag. - Ending CDATA at the last
]]>instead of the first.
How to talk through it
- 1Clarify. Must the code be one single tag? Can CDATA appear outside a tag? Which characters count as a name?
- 2Name the pattern. This is bracket matching where the brackets are named tags: a stack of open names.
- 3List the four cases. CDATA, end tag, start tag, text. Check them in that order.
- 4Guard the edges. Text or CDATA needs an open tag, and nothing may follow once the stack empties.
- 5Test out loud. Run crossed tags, a 10-letter name and CDATA holding a fake end tag before saying you are done.