-
Notifications
You must be signed in to change notification settings - Fork 3
/
TagContentExtractor.java
62 lines (53 loc) Β· 2.03 KB
/
TagContentExtractor.java
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
// https://www.hackerrank.com/challenges/tag-content-extractor/problem
import java.util.Scanner;
public class TagContentExtractor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int queries = scanner.nextInt();
scanner.nextLine();
while (queries-- > 0) {
String string = scanner.nextLine();
printValidTokens(string);
}
}
private static void printValidTokens(String string) {
String token = null;
boolean flag = true;
for (int index = 0, startIndex = -1 ; index < string.length() ; index++) {
if (string.charAt(index) == '<') {
Lexene lexene = new Lexene(string, index);
if (lexene.isOpeningTag) {
index += lexene.token.length() + 1;
token = lexene.token;
startIndex = index + 1;
} else {
if (lexene.token.equals(token) && index - startIndex > 0 && !lexene.token.equals("")) {
System.out.println(string.substring(startIndex, index));
flag = false;
}
token = null;
}
}
}
if (flag) {
System.out.println("None");
}
}
private static class Lexene {
String token;
boolean isOpeningTag;
Lexene(String string, int startIndex) {
StringBuilder accumulator = new StringBuilder();
for (int index = startIndex + 1 ; index < string.length() ; index++) {
if (string.charAt(index) == '>') {
break;
}
accumulator.append(string.charAt(index));
}
token = accumulator.length() > 0
? accumulator.charAt(0) == '/' ? accumulator.substring(1) : accumulator.toString()
: "";
isOpeningTag = accumulator.length() > 0 && accumulator.charAt(0) != '/';
}
}
}