question 344 Algorithms & Complexity · medium
Validate the nesting of HTML tags
An email template editor rejects templates whose tags don't nest properly, and points at the first problem. Tags arrive already split out, like "<ul>", "</ul>" and "<br/>". Write first_tag_error(tags).
Function
first_tag_error(tags)tagsa list of tag texts: opening
<name>, closing </name>, or self-closing <name/> (which never needs closing)Returnsthe index of the first closing tag that doesn't close the most recently opened tag still open (or closes when none is open);
len(tags) if every closing tag was fine but some tag is left open; -1 if the nesting is validNamescompared exactly as written, without the brackets and slashes
Examples
callfirst_tag_error(['<p>', '<b>', '</p>', '</b>'])returns2
callfirst_tag_error(['<ul>', '<li>', '</li>', '<li>', '<br/>', '</li>', '</ul>'])returns-1
callfirst_tag_error(['<div>', '<p>', '</p>'])returns3