-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path14_reverseInParanthesis
105 lines (71 loc) · 2.59 KB
/
14_reverseInParanthesis
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
105
String solution(String inputString) {
StringBuilder sb = new StringBuilder();
Stack<StringBuilder> stack = new Stack<>();
for(char c : inputString.toCharArray()){
if(c == '('){
stack.push(new StringBuilder());
}
else if(c == ')'){
StringBuilder top = stack.pop().reverse();
if(!stack.isEmpty()){
stack.peek().append(top);
}
else{
sb.append(top);
}
}
else if(!stack.isEmpty()){
stack.peek().append(c);
}
else{
sb.append(c);
}
}
return sb.toString();
}
//Refer code to this website
//https://www.onlinegdb.com/edit/mMxny3DZ7
// or copy paste the below code in any compiler
/******************************************************************************
import java.util.*;
public class Main
{
public static void main(String[] args) {
String s = "foo(bar(baz))blim";
StringBuilder ans = new StringBuilder();
Stack<StringBuilder> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
System.out.println("1.Before Push Stack : "+stack);
stack.push(new StringBuilder());
System.out.println("1.After Push Stack : "+stack);
}
else if (c == ')') {
System.out.println("2.Before Pop Stack : "+stack);
StringBuilder top = stack.pop().reverse();
System.out.println("2.Top : "+top);
if (!stack.isEmpty()) {
stack.peek().append(top);
System.out.println("2.Not Empty Stack after POP : "+stack);
}
else {
System.out.println("2.Empty Stack after POP : "+stack);
ans.append(top);
System.out.println("2.After appending reversed string to ans : "+ans);
}
}
else if (!stack.isEmpty()){
System.out.println("3.Before Peek Stack : "+stack);
stack.peek().append(c);
System.out.println("3.After Peek Stack : "+stack);
}
else {
System.out.println("4.Before append : "+ans);
ans.append(c);
System.out.println("4.After append : "+ans);
}
}
System.out.print(ans.toString());
}
}
*******************************************************************************/