Matching format tags

Write code · Medium · §5.1 Stacks

tokens holds, in order, the formatting tags written in a post. "<name>" opens the format named name, and "</name>" closes it. A closing tag must have the same name as the most recently opened tag that is still open. A closing tag that appears when no tag is open also breaks this rule.

Complete the function solution, which returns the position of the first closing tag that breaks the rule. Positions are counted from 0 at the start of tokens. If no tag breaks the rule but some tags are still open at the end, return len(tokens). If all the tags match, return -1.

Function

solution(tokens)

Constraints

Examples

tokensresult
['<b>', '<i>', '</i>', '</b>']-1
['<em>', '</em>', '<b>', '</i>', '</b>']3

Starter code

def solution(tokens):
    answer = 0
    return answer

Solve this problem in your browser

Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.