Skip to content

Commit 4fd752c

Browse files
committed
add solution of problem 394: decode string
1 parent 2e9540f commit 4fd752c

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

DecodeString394/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Given an encoded string, return it's decoded string.
2+
3+
The encoding rule is: `k[encoded_string]`, where the *encoded_string* inside the square brackets is being repeated exactly *k* times. Note that *k* is guaranteed to be a positive integer.
4+
5+
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
6+
7+
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, *k*. For example, there won't be input like `3a` or `2[4]`.
8+
9+
#####Examples:
10+
```
11+
s = "3[a]2[bc]", return "aaabcbc".
12+
s = "3[a2[c]]", return "accaccacc".
13+
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
14+
```
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
public class Solution {
2+
public String decodeString(String s) {
3+
if (s == null)
4+
return "";
5+
6+
int sLen = s.length();
7+
int idx = 0;
8+
StringBuilder sb = new StringBuilder();
9+
10+
while (idx < sLen) {
11+
int idxOfFirstLetter = idx;
12+
while (idx < sLen && !(s.charAt(idx) >= '0' && s.charAt(idx) <= '9')) {
13+
idx++;
14+
}
15+
16+
int idxOfFirstDigit = idx;
17+
while (idx < sLen && s.charAt(idx) != '[') {
18+
idx++;
19+
}
20+
21+
sb.append(s.substring(idxOfFirstLetter, idxOfFirstDigit));
22+
if (idx < sLen) {
23+
int factor = Integer.valueOf(s.substring(idxOfFirstDigit, idx));
24+
25+
idx++;
26+
27+
int startIdx = idx;
28+
int cnt = 0;
29+
while (idx < sLen && (s.charAt(idx) != ']' || cnt > 0)) {
30+
if (s.charAt(idx) == '[')
31+
cnt++;
32+
if (s.charAt(idx) == ']')
33+
cnt--;
34+
idx++;
35+
}
36+
37+
String subStr = decodeString(s.substring(startIdx, idx));
38+
39+
for (int i = 0; i < factor; i++) {
40+
sb.append(subStr);
41+
}
42+
43+
idx++;
44+
}
45+
}
46+
47+
return sb.toString();
48+
}
49+
}

0 commit comments

Comments
 (0)