-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode String.java
More file actions
30 lines (29 loc) · 936 Bytes
/
Decode String.java
File metadata and controls
30 lines (29 loc) · 936 Bytes
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
public class Solution{
int index = 0;
public String decodeString(String s) {
StringBuilder re = new StringBuilder();
int n = 0;
while(index < s.length()) {
// is digit
if(Character.isDigit(s.charAt(index))) {
while(Character.isDigit(s.charAt(index))) {
n = 10*n + s.charAt(index++)-'0';
}
// skip "["
index++;
String nested = decodeString(s);
while(n > 0) {
n--;
re.append(nested);
}
}
// is letter
else if(Character.isLetter(s.charAt(index))) {
re.append(s.charAt(index++));
}
// is ], skip
else if(s.charAt(index++) == ']') return re.toString();
}
return re.toString();
}
}