-
Notifications
You must be signed in to change notification settings - Fork 46
/
_394.java
32 lines (30 loc) · 981 Bytes
/
_394.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
/**
* LeetCode 394 - Decode String
*
* Top-down approach
*/
public class _394 {
int ptr;
char[] a;
private String repeatToken() {
StringBuilder inner = new StringBuilder(), outer = new StringBuilder();
int num = 0;
while (Character.isDigit(a[ptr])) num = num * 10 + a[ptr++] - '0';
ptr++; // skip [
while (a[ptr] != ']')
if (Character.isDigit(a[ptr])) inner.append(repeatToken());
else inner.append(a[ptr++]);
ptr++; // skip ]
String innerStr = inner.toString();
for (; num > 0; num--) outer.append(innerStr);
return outer.toString();
}
public String decodeString(String s) {
a = s.toCharArray();
StringBuilder builder = new StringBuilder();
for (ptr = 0; ptr < s.length(); )
if (Character.isDigit(a[ptr])) builder.append(repeatToken());
else builder.append(a[ptr++]);
return builder.toString();
}
}