forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
32 lines (29 loc) · 1014 Bytes
/
Solution.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
package g0301_0400.s0394_decode_string;
// #Medium #Top_100_Liked_Questions #String #Stack #Recursion #Level_1_Day_14_Stack #Udemy_Strings
// #Big_O_Time_O(n)_Space_O(n) #2022_07_15_Time_1_ms_(87.68%)_Space_41.2_MB_(83.30%)
public class Solution {
private int i = 0;
public String decodeString(String s) {
int count = 0;
StringBuilder sb = new StringBuilder();
while (i < s.length()) {
char c = s.charAt(i);
i++;
if (Character.isLetter(c)) {
sb.append(c);
} else if (Character.isDigit(c)) {
count = count * 10 + Character.getNumericValue(c);
} else if (c == ']') {
break;
} else if (c == '[') {
// sub problem
String repeat = decodeString(s);
while (count > 0) {
sb.append(repeat);
count--;
}
}
}
return sb.toString();
}
}