-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringDecode.java
30 lines (28 loc) · 991 Bytes
/
StringDecode.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
class Solution {
public String decodeString(String s) {
Stack<Integer> intStack = new Stack<>();
Stack<StringBuilder> sbStack = new Stack<>();
StringBuilder stringBuilder = new StringBuilder();
int n = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
n = n * 10 + (c - '0');
} else if (c == '[') {
intStack.push(n);
n = 0;
sbStack.push(stringBuilder);
stringBuilder = new StringBuilder();
} else if (c == ']') {
int k = intStack.pop();
StringBuilder temp = stringBuilder;
stringBuilder = sbStack.pop();
while (k-- > 0) {
stringBuilder.append(temp);
}
} else {
stringBuilder.append(c);
}
}
return stringBuilder.toString();
}
}