Skip to the code
cf.
+25 XP

#254 Validate Nested Markup Tags

medium

A markup linter receives a document already split into tokens. A token is one of: an opening tag like <div>, a closing tag like </div>, a self-closing tag like <br/>, or plain text (any token that doesn't start with <).

Write validTags(tokens) that returns true if every opening tag is closed by a closing tag with the same name, tags never cross (so <b><i></b></i> is invalid), and no closing tag appears without a matching open tag. Self-closing tags and text never need closing.

Example 1

Input: tokens = ["<div>","<p>","hello","</p>","</div>"]
Output: true

p closes inside div, then div closes.

Example 2

Input: tokens = ["<div>","<span>","</div>","</span>"]
Output: false

div closes while span is still open inside it.

Constraints

  • 0 <= tokens.length <= 10^4
  • Tag names have lowercase letters and digits.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).