-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decode String
39 lines (35 loc) · 1.14 KB
/
Decode String
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
class Solution {
public String decodeString(String s) {
Stack<String> sol = new Stack();
Stack<Integer> multiplier = new Stack();
String solution = "";
int number = 0;
for (int i=0; i<s.length(); i++){
if (Character.isDigit(s.charAt(i))){
number = number * 10 + Character.getNumericValue(s.charAt(i));
}else if (s.charAt(i) == '['){
multiplier.push(number);
number = 0;
sol.push(solution);
solution = "";
}else if (s.charAt(i) == ']'){
int mul = multiplier.pop();
String poper = sol.pop();
solution = poper + repeat(solution, mul);
}else
{
solution += s.charAt(i);
}
}
return solution;
}
public String repeat(String toRepeat, int repeatCount) {
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < repeatCount) {
sb.append(toRepeat);
i++;
}
return sb.toString();
}
}