-
Notifications
You must be signed in to change notification settings - Fork 0
/
374-DecodeString.java
40 lines (39 loc) · 1.28 KB
/
374-DecodeString.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
31
32
33
34
35
36
37
38
39
40
// 394. Decode String
class Solution {
public String decodeString(String s) {
if (s == null || s.length() == 0) {
return s ;
}
Stack<Integer> integerStack = new Stack<>();
Stack<String> stringStack = new Stack<>();
String result = "";
int ptr = 0;
while(ptr < s.length()) {
char curr = s.charAt(ptr);
if (Character.isDigit(curr)) {
int num = 0;
while (Character.isDigit(s.charAt(ptr))) {
num = num * 10 + s.charAt(ptr) - '0';
ptr++;
}
integerStack.push(num);
} else if (curr == '[') {
stringStack.push(result);
result = "";
ptr++;
} else if (curr == ']') {
StringBuilder sb = new StringBuilder(stringStack.pop());
int count = integerStack.pop();
for(int i = 0; i < count; i++) {
sb.append(result);
}
result = sb.toString();
ptr++;
} else {
result += curr;
ptr++;
}
}
return result;
}
}