Repository navigation
Expand file tree
/
Copy pathproblem394.java
More file actions
65 lines (48 loc) · 1.48 KB
/
Copy pathproblem394.java
File metadata and controls
65 lines (48 loc) · 1.48 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
//394. Decode String
import java.util.Stack;
public class problem394 {
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static String decodeString(String s) {
Stack<String> st = new Stack<>();
int i=0;
StringBuffer temp = new StringBuffer();
while(i<s.length())
{
String t = String.valueOf(s.charAt(i));
if(t.equals("]"))
{
temp.setLength(0);
while (!st.peek().equals("[")) {
temp.insert(0, st.pop());
}
st.pop();
StringBuffer x = new StringBuffer();
while (!st.isEmpty() && isInteger(st.peek())) {
x.insert(0,st.pop());
}
String temp1 = temp.toString().repeat(Integer.parseInt(x.toString()));
st.push(temp1);
}
else{
st.push(t);
}
i++;
}
temp.setLength(0);
while (!st.isEmpty()) {
temp.insert(0, st.pop()); // Maintain correct order
}
return temp.toString();
}
public static void main(String[] args) {
String a="3[a2[c]]";
System.out.println(decodeString(a));
}
}