forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsValidSerialization.java
More file actions
47 lines (42 loc) · 1.51 KB
/
IsValidSerialization.java
File metadata and controls
47 lines (42 loc) · 1.51 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
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
public class IsValidSerialization {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"));;
}
static class Solution {
public boolean isValidSerialization(String preorder) {
int diff = 1;
String[] nodes = preorder.split(",");
for (String n:nodes) {
diff -= 1;
if (diff < 0) return false;
if (!"#".equals(n)) diff += 2;
}
return diff == 0;
}
public boolean isValidSerialization2(String preorder) {
Stack<String> stack = new Stack<>();
String[] nodes = preorder.split(",");
for (String n : nodes) {
stack.push(n);
while (stack.size() >= 3) {
String pop1 = stack.pop();
String pop2 = stack.pop();
String pop3 = stack.pop();
if ("#".equals(pop1) && "#".equals(pop2) && !"#".equals(pop3)) {
stack.push("#");
}else {
stack.push(pop3);
stack.push(pop2);
stack.push(pop1);
break;
}
}
}
return stack.size() == 1 && "#".equals(stack.peek());
}
}
}