forked from super30admin/DFS-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_string.java
26 lines (25 loc) · 961 Bytes
/
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
class Solution {
int index = 0;
String decodeString(String s) {
StringBuilder result = new StringBuilder();
while (index < s.length() && s.charAt(index) != ']') {
if (!Character.isDigit(s.charAt(index)))
result.append(s.charAt(index++));
else {
int k = 0;
// build k while next character is a digit
while (index < s.length() && Character.isDigit(s.charAt(index)))
k = k * 10 + s.charAt(index++) - '0';
// ignore the opening bracket '['
index++;
String decodedString = decodeString(s);
// ignore the closing bracket ']'
index++;
// build k[decodedString] and append to the result
while (k-- > 0)
result.append(decodedString);
}
}
return new String(result);
}
}