Web Pages

Interview

Time limit1sMemory limit128 MB

Summary
For each line of HTML-looking text, decide whether every opening tag has a matching closing tag and all tags nest properly.
Level

Medium4 of 10

Topics
Stack, String, Implementation, Brute force
Solved
No attempts yet

Problem

You are probably familiar with HTML, the markup language used to create web pages. HTML code contains a number of tags, which are expected to follow certain rules.

In this problem we are concerned with two of these rules:

  1. Every opening tag must have a corresponding closing tag.
  2. All tags must be properly nested.

Tags are marked by angle brackets that contain a keyword, such as <body> or <strong>. These are opening tags; the corresponding closing tags place a / before the keyword, i.e. </body> and </strong>. A tag can be both opening and closing, such as <br />, which satisfies rule 1.

To be properly nested, if a tag is opened inside another tag, it must be closed before the outer tag closes. For example:

  • <body> <strong> </strong> </body> is properly nested.
  • <body> <strong> </body> </strong> is not, and breaks rule 2.

If there are no tags present, the text complies with both rules.

Attributes may appear inside an opening tag, such as:

<a href="http://www.nzprogcontest.org.nz">This is a link</a>

A closing tag only has to match the keyword, not the attributes.

Input

The input consists of a number of lines of HTML code, each line containing from 0 to 255 characters. The last line contains a single # character — do not process this line. Each line contains zero or more tags. No angle bracket appears unless it is part of a properly formed tag.

For each line, determine whether or not it satisfies the rules described above. Each line is evaluated independently.

Output

The output consists of a single line for each line of input. Each line contains either the word legal or the word illegal.

Examples1

  1. Example 1

    Input
    <body> <strong>Oops, this is</body> naughty </strong>
    <body> <strong>Hello</strong> <br /> </body>
    Just text, no tags.
    <p> Oh dear, we are missing something.
    <a href="http://www.nzprogcontest.org.nz">This is a link</a>
    #
    
    Expected output
    illegal
    legal
    legal
    illegal
    legal