1684. Markup Nesting Check

Medium3.5 points estimatedStackString

A tiny markup language mixes plain text with tags. An opening tag looks like <name>, a closing tag like </name> and a self-closing tag like <name/>, where name is 1 to 10 lowercase letters. In doc, every < must begin a well-formed tag that ends at the very next >; a > that does not end a tag is invalid. A / or a letter outside a tag is plain text.

Return true if every tag is well-formed, every closing tag matches the most recently opened tag that is still open, and no tag is left open at the end. Self-closing tags neither open nor close anything. A single left-to-right pass with a stack of names runs in O(n) time and O(n) space.

Example 1

Input:
doc = "<a><b>hi</b></a>"
Output:
true
Explanation:

Both tags are closed in stack order, so the document is well nested.

Example 2

Input:
doc = "<a></b>"
Output:
false
Explanation:

The closing tag b does not match the open tag a.

Example 3

Input:
doc = "<br/>x<i>y</i>"
Output:
true
Explanation:

The self-closing tag opens nothing and the i tag is closed properly.

Constraints

1 ≤ doc.length ≤ 2000; doc consists of lowercase letters, '<', '>' and '/'

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…