-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlParser.java
More file actions
73 lines (62 loc) · 2.6 KB
/
HtmlParser.java
File metadata and controls
73 lines (62 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
/**
* The HtmlParser class is responsible for parsing HTML content and extracting the deepest text.
*/
public class HtmlParser {
/**
* Parses the given list of HTML lines and extracts the deepest text.
*
* @param lines the list of HTML lines to parse
* @return the deepest text found in the HTML content
* @throws MalformedHtmlException if the HTML content is malformed
*/
public String getDeepestText(List<String> lines) throws MalformedHtmlException {
Deque<String> tagDeque = new LinkedList<>();
int maxDepth = -1;
String deepestText = "";
for (String rawLine : lines) {
String line = rawLine.trim();
if (line.isEmpty()) continue;
if (isTag(line)){
processTagLine(line, tagDeque);
} else {
deepestText = updateDeepestText(line, tagDeque, deepestText, maxDepth);
maxDepth = Math.max(maxDepth, tagDeque.size());
}
}
if(!tagDeque.isEmpty()) throw new MalformedHtmlException();
return deepestText;
}
private void processTagLine(String line, Deque<String> tagDeque) throws MalformedHtmlException {
if (isClosingTag(line)) processClosingTag(line, tagDeque);
else processOpeningTag(line, tagDeque);
}
private void processClosingTag(String line, Deque<String> tagDeque) throws MalformedHtmlException {
String tagName = extractTagName(line, true);
if (tagDeque.isEmpty() || !tagDeque.peek().equals(tagName)) throw new MalformedHtmlException();
tagDeque.pop();
}
private void processOpeningTag(String line, Deque<String> tagDeque) throws MalformedHtmlException {
String tagName = extractTagName(line, false);
if (tagName.contains(" ")) throw new MalformedHtmlException();
tagDeque.push(tagName);
}
private String updateDeepestText(String text, Deque<String> tagDeque, String currentDeepestText, int currentMaxDepth) {
int currentDepth = tagDeque.size();
if (currentDepth > currentMaxDepth) return text;
return currentDeepestText;
}
private boolean isTag(String line) {
return line.startsWith("<") && line.endsWith(">");
}
private boolean isClosingTag(String line) {
return line.startsWith("</");
}
private String extractTagName(String line, boolean closing) {
return closing
? line.substring(2, line.length() - 1).trim()
: line.substring(1, line.length() - 1).trim();
}
}