-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0394-decode-string.java
33 lines (24 loc) · 1005 Bytes
/
0394-decode-string.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
class Solution {
int index = 0;
public String decodeString(String s) {
StringBuilder decoded = new StringBuilder();
while (index < s.length() && s.charAt(index) != ']') {
// character is a letter of encoded
if (!Character.isDigit(s.charAt(index))) decoded.append(s.charAt(index++));
// character is number or [ ]
else {
int k = 0;
// case: number
while (index < s.length() && Character.isDigit(s.charAt(index))) k = k * 10 + s.charAt(index++) - '0';
// case: [
index++;
String answer = decodeString(s);
// case: ]
index++;
// add k*encoded to decoded
while (k-- > 0) decoded.append(answer);
}
}
return new String(decoded);
}
}