-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSampleDemo.java
86 lines (74 loc) · 2 KB
/
SampleDemo.java
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
import java.util.*;
public class SampleDemo {
static public void main(String []ar) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.next();
System.out.print(decodeString(str) +"\n");
sc.close();
}
//recursive function
static Stack<String> stack = new Stack<String>();
static String result = "";
static void decode(char []s, int index) {
if(index == s.length) {
result = stack.peek();
return;
}
//if character is a '['
if(s[index] == '[');
// if character is a ']'
else if(s[index] == ']')
{
String temp = stack.peek();
stack.pop();
//pop integer x from stack
int x = Integer.valueOf(stack.peek());
stack.pop();
for(String j = temp;x>1;x--)
temp = temp + j;
String temp1 = stack.isEmpty()==false?stack.peek(): "";
if(!temp1.isEmpty() && !(temp1.charAt(0) - '0' < 10)) {
stack.pop();
temp1 = temp1 + temp;
stack.add(temp1);
}
else {
stack.add(temp);
}
}
//char is a digit
else if (s[index] - '0' < 10) {
String temp = stack.isEmpty() == false ? stack.peek() : "";
if (!temp.isEmpty() && temp.charAt(0) - '0' < 10 && s[index - 1] - '0' < 10) {
stack.pop();
temp = temp + s[index];
stack.add(temp);
}
else {
temp = String.valueOf(s[index]);
stack.add(temp);
}
}
else if (s[index] - 'a' < 26) {
String temp = stack.isEmpty() == false ? stack.peek() : "";
if (!temp.isEmpty() && temp.charAt(0) - 'a' >= 0
&& temp.charAt(0) - 'a' < 26) {
stack.pop();
temp = temp + s[index];
stack.add(temp);
}
else {
temp = String.valueOf(s[index]);
stack.add(temp);
}
}
// Recursive call for next index
decode(s, index + 1);
}
static String decodeString(String string)
{
decode(string.toCharArray(), 0);
return result;
}
}