Repository navigation
Expand file tree
/
Copy pathQ3_2.java
More file actions
51 lines (43 loc) · 1.5 KB
/
Copy pathQ3_2.java
File metadata and controls
51 lines (43 loc) · 1.5 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
package datastructure;
import java.util.Stack;
public class Q3_2 {
public String solution(String s){
String answer = "";
Stack<String> st = new Stack<>();
for (char x : s.toCharArray()) {
if(x == ')') {
String tmp = "";
while(!st.isEmpty()) {
String c = st.pop();
if(c.equals("(")) {
String num = "";
while(!st.isEmpty() && Character.isDigit(st.peek().charAt(0))) {
num = st.pop() + num;
}
String res = "";
int cnt = 0;
if(num.equals("")) cnt = 1;
else cnt = Integer.parseInt(num);
for(int i = 0; i < cnt; i++) res += tmp;
st.push(res);
break;
}
tmp = c + tmp;
}
}
else st.push(String.valueOf(x));
}
for (String s1 : st) {
answer += s1;
}
return answer;
}
public static void main(String[] args){
Q3_2 T = new Q3_2();
System.out.println(T.solution("3(a2(b))ef"));
System.out.println(T.solution("2(ab)k3(bc)"));
System.out.println(T.solution("2(ab3((cd)))"));
System.out.println(T.solution("2(2(ab)3(2(ac)))"));
System.out.println(T.solution("3(ab2(sg))"));
}
}