Repository navigation
Expand file tree
/
Copy pathB1.java
More file actions
75 lines (65 loc) · 2.26 KB
/
Copy pathB1.java
File metadata and controls
75 lines (65 loc) · 2.26 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
import java.util.Stack;
public class B1 {
private static String expandEquation(String eqn) {
if (eqn == null || eqn.length() == 0) {
return null;
}
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
int i = 0;
// 0 represents the same value, 1 represents toggle
s.push(0);
while (i < eqn.length()) {
if (eqn.charAt(i) == '-') {
if (s.peek() == 1) {
sb.append('+');
} else {
sb.append('-');
}
} else if (eqn.charAt(i) == '+') {
if (s.peek() == 1) {
sb.append('-');
} else {
sb.append('+');
}
} else if (eqn.charAt(i) == '(' && i > 0) {
char preSign = eqn.charAt(i - 1);
// For nested brackets, if the outtermost sign is a
// negative sign, then check if we need to negate
// the sign.
//
// If the outtermost sign is a positive sign,
// then push the previous toggle value as
// positive sign's don't negate anything.
if (preSign == '-') {
if (s.peek() == 1) {
s.push(0);
} else {
s.push(1);
}
} else {
s.push(s.peek());
}
} else if (eqn.charAt(i) == ')') {
s.pop();
} else {
sb.append(eqn.charAt(i));
}
++i;
}
return sb.toString();
}
public static void main(String[] args) {
String equation1 = "-(a+b)";
String equation2 = "-(a+b)+c-(d-e)";
String equation3 = "a-b+(c-d)";
String equation4 = "a-(b+c)";
String equation5 = "a-(b-c-(d+e))-f";
System.out.println(expandEquation(equation1));
System.out.println(expandEquation(equation2));
System.out.println(expandEquation(equation3));
System.out.println(expandEquation(equation4));
System.out.println(expandEquation(equation5));
return;
}
}