-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode String.java
More file actions
47 lines (38 loc) · 1.3 KB
/
Decode String.java
File metadata and controls
47 lines (38 loc) · 1.3 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
class Solution {
public String decodeString(String s) {
if(s.length() == 1)
return s;
Stack<String> result = new Stack<>();
int index=0;
while(index != s.length())
{
if(s.charAt(index) != ']')
result.push(String.valueOf(s.charAt(index)));
else
{
String num = "";
String str = "";
while(!result.peek().equals("["))
str = result.pop() + str;
result.pop();
while(!result.empty() && result.peek().chars().allMatch(Character::isDigit))
num = result.pop() + num;
String decode = repeatString(Integer.parseInt(num), str);
result.push(decode);
}
index++;
}
String decoded_string = "";
Iterator<String> itr = result.iterator();
while(itr.hasNext())
decoded_string+=itr.next();
return decoded_string;
}
public String repeatString(int rep, String val)
{
if(rep == 1)
return val;
String decode = val + repeatString(rep-1, val);
return decode;
}
}