forked from yuzhangcmu/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SnapChat.java
executable file
·104 lines (87 loc) · 2.17 KB
/
SnapChat.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package Algorithms;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
<a><b>
<c>foo</c>
<c>bar</c>
</b>
<d>blah</d>
</a>
Node
name
text
List<Node> children
Tokenizer
Token getToken();
Token
type //BEGIN, TEXT, END
value
(BEGIN, "a"),
(BEGIN, "b"),
(BEGIN, "c"),
(TEXT, "foo"),
(END, "c"),
(BEGIN, "c"),
(TEXT, "bar"),
(END, "c"),
(END, "b"),
(BEGIN, "d"),
(TEXT, "blah"),
(END, "d")
(END, "a")
*/
public class SnapChat {
public class Tokenizer {
public Token getToken() {
return null;
}
}
public class Token {
String type;
String value;
}
public class Node {
public String name;
public String text;
public List<Node> children;
public Node(String name, String text) {
super();
this.name = name;
this.text = text;
this.children = new ArrayList<Node>();
}
}
public Node generateTree(Tokenizer tokennizer) throws Exception {
Node parent = null;
Node root = null;
Stack<Node> stk = new Stack<Node>();
while (true) {
Token toke = tokennizer.getToken();
if (toke == null) {
break;
}
if (toke.type == "TEXT") {
if (parent == null) {
throw new Exception("The format is wrong.");
}
parent.text = toke.value;
} else if (toke.type == "BEGIN"){
Node node = new Node(toke.value, "");
if (parent == null) {
parent = node;
root = parent;
} else {
stk.push(parent);
parent.children.add(node);
parent = node;
}
//parent.children.add(node);
} else if (toke.type == "END"){
parent = stk.pop();
}
}
return root;
}
}