forked from sherxon/AlgoDS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamProcessing_9.java
More file actions
104 lines (98 loc) · 2.94 KB
/
Copy pathStreamProcessing_9.java
File metadata and controls
104 lines (98 loc) · 2.94 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
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 adventofcode;
import java.util.Scanner;
import java.util.Stack;
/**
* Why Did you create this class? what does it do?
*/
@SuppressWarnings("Duplicates") public class StreamProcessing_9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (s.equals("1"))
break;
builder.append(s);
}
System.out.println(solve2(builder));
}
private static int solve(StringBuilder builder) {
if (builder == null || builder.length() == 0)
return 0;
// clean ignore garbage
StringBuilder s = new StringBuilder();
boolean ignore = false;
for (int i = 0; i < builder.length(); i++) {
char current = builder.charAt(i);
if (ignore) {
ignore = false;
continue;
}
if (current == '!') {
ignore = true;
continue;
}
s.append(current);
}
// clean garbage
int i = 0;
while (i < s.length()) {
int start = s.indexOf("<");
if (start < 0)
break;
int end = s.indexOf(">", start);
if (end < 0)
throw new IllegalArgumentException("wrong input");
s.delete(start, end + 1);
i = end + 1;
}
Stack<Character> stack = new Stack<>();
int sum = 0;
for (int j = 0; j < s.length(); j++) {
char current = s.charAt(j);
if (current == ',')
continue;
if (current == '{') {
stack.add(current);
} else {
sum += stack.size();
stack.pop();
}
}
return sum;
}
private static int solve2(StringBuilder builder) {
if (builder == null || builder.length() == 0)
return 0;
// clean ignore garbage
StringBuilder s = new StringBuilder();
boolean ignore = false;
for (int i = 0; i < builder.length(); i++) {
char current = builder.charAt(i);
if (ignore) {
ignore = false;
continue;
}
if (current == '!') {
ignore = true;
continue;
}
s.append(current);
}
// clean garbage
int i = 0;
int sum = 0;
while (i < s.length()) {
int start = s.indexOf("<");
if (start < 0)
break;
int end = s.indexOf(">", start);
if (end < 0)
throw new IllegalArgumentException("wrong input");
s.delete(start, end + 1);
sum += (end - start - 1);
i = end + 1;
}
return sum;
}
}