Найдите отсутствующий конечный тег в данном HTML-коде
Опубликовано: 9 Января, 2022
Учитывая строку htmlCode, которая представляет собой HTML-код веб-страницы, задача состоит в том, чтобы найти отсутствующий конечный тег в HTML-коде.
Примеры:
Ввод: htmlCode = "<! DOCTYPE html>"
<html>
<head>
<название>
GeeksforGeeks
</title>
</head>
<body>
<кнопка>
</body>
</html> "
Вывод: </button>
Ввод: htmlCode = "<! DOCTYPE html>"
<html>
<body>
<p> Здравствуйте </p>
</html> "
Вывод: </body>
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Подход: Идея состоит в том, чтобы использовать стек для отслеживания текущих начальных тегов в HTML-коде и наличия конечного тега, не совпадающего с вершиной стека, который обозначает начальный тег. Затем первым должен быть закрыт тег, который находится наверху стека. Следовательно, вершиной стека будет желаемый отсутствующий тег в HTML-коде.
Below is the implementation of the above approach:
Python
# Python implementation to find the # the missing end in the HTML code # Function to Auto complete the # missing tag in the html Codedef autoComplete(s): # Split the html Code in line linesOfCode = list(s.strip().split("
")) # Tags which are self closed doesn"t # needs to be closed selfClosedTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"] n = len(linesOfCode) stack = [] # Loop to iterate over the # lines of code for i in range(n): j = 0 # Current Line line = linesOfCode[i] while j < len(linesOfCode[i]): # Condition to check if the current # character is a end tag in the code if j + 1 < len(line) and line[j] == "<" and line[j + 1] == "/": tag = [] j += 2 # Loop to get the tag while j < len(line) and "a" <= line[j] <= "z": tag.append(line[j]) j += 1 while j < len(line) and line[j] != ">": j += 1 if stack[-1] != tag: tag = stack[-1] return "</" + "".join(tag) + ">" stack.pop() # Conditio to check if the current # character denotes the code is # of the HTML 5 elif j + 1 < len(line) and line[j] == "<" and line[j] == "!": continue # Condition to check if the current # tag is a start tag of the HTML Code elif line[j] == "<": tag = [] j += 1 # Loop to get the tag of the HTML while j < len(line) and "a" <= line[j] <= "z": tag.append(line[j]) j += 1 while j < len(line) and line[j] != ">": j += 1 # Condition to check if the # current tag is not a self closed tag if "".join(tag) not in selfClosedTags: stack.append(tag) j += 1 # Condition to check if any tag # is unbalanced then return that tag if stack: tag = stack.pop() return "</" + "".join(tag) + ">" return -1 # Driver Codeif __name__ == "__main__": s = """<! DOCTYPE html><html><head> <title> GeeksforGeeks </title></head><body> <button></body></html>""" tag = autoComplete(s) print(tag) |
Output:
</button>