Skip to content

Instantly share code, notes, and snippets.

@josephbill
Created April 24, 2025 09:40
Show Gist options
  • Save josephbill/71c3558040d3d74248048054107c633b to your computer and use it in GitHub Desktop.
Save josephbill/71c3558040d3d74248048054107c633b to your computer and use it in GitHub Desktop.
HTML Elements
Have the function HTMLElements(str) read the str parameter being passed which will be a string of HTML DOM elements and plain text. The elements that will be used are: b, i, em, div, p. For example: if str is "<div><b><p>hello world</p></b></div>" then this string of DOM elements is nested correctly so your program should return the string true.
If a string is not nested correctly, return the first element encountered where, if changed into a different element, would result in a properly formatted string. If the string is not formatted properly, then it will only be one element that needs to be changed. For example: if str is "<div><i>hello</i>world</b>" then your program should return the string div because if the first <div> element were changed into a <b>, the string would be properly formatted.
Examples
Input: "<div><div><b></b></div></p>"
Output: div
Input: "<div>abc</div><p><em><i>test test test</b></em></p>"
@4512yasir
Copy link

Function HTMLElements(str):
stack = [ ]
tags = extract all tags from str using regex

for each tag in tags:
    if tag is opening:
        push tag to stack
    else:
        if stack is empty:
            return tag name without '/'
        top = top of stack
        if tag matches top:
            pop stack
        else:
            return top tag name

if stack is empty:
    return "true"
else:
    return first tag name in stack

@dennissammy77
Copy link

In this instance
"

helloworld"
should the return be strong or div. Cause it is the first error that does not match the closing , strong and i do not match.
changing strong to i would complete the nest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment