-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path394_decode_string.java
More file actions
46 lines (41 loc) · 1.4 KB
/
394_decode_string.java
File metadata and controls
46 lines (41 loc) · 1.4 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
private int index;
public String decodeString(String s) {
if (s == null || s.length() == 0)
return "";
this.index = 0;
return extractSubstring(s);
}
private int extractNum(String s) {
StringBuilder numBuilder = new StringBuilder();
while (s.charAt(this.index) != '[') {
numBuilder.append(s.charAt(this.index));
this.index ++;
}
return Integer.valueOf(numBuilder.toString());
}
private String extractSubstring(String s) {
if (this.index >= s.length())
return "";
StringBuilder builder = new StringBuilder();
while (this.index < s.length() && s.charAt(this.index) != ']') {
char c = s.charAt(this.index);
if (c >= '0' && c <= '9') {
int num = extractNum(s);
this.index ++;
String str = extractSubstring(s);
builder.append(concateDecodedString(num, str));
} else {
builder.append(c);
}
this.index ++;
}
return builder.toString();
}
private String concateDecodedString(int num, String substring) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < num; i++)
builder.append(substring);
return builder.toString();
}
}