-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDecodeString.java
More file actions
46 lines (37 loc) · 1.32 KB
/
DecodeString.java
File metadata and controls
46 lines (37 loc) · 1.32 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
package stack;
import java.util.Deque;
import java.util.LinkedList;
/**
* Description: https://leetcode.com/problems/decode-string
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class DecodeString {
public String decodeString(String s) {
Deque<Integer> numbersStack = new LinkedList<>();
int currentNumber = 0;
Deque<StringBuilder> valuesStack = new LinkedList<>();
valuesStack.push(new StringBuilder());
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
currentNumber = 10 * currentNumber + Character.getNumericValue(c);
} else if (c == '[') {
numbersStack.push(currentNumber);
currentNumber = 0;
valuesStack.push(new StringBuilder());
} else if (c == ']') {
int times = numbersStack.pop();
StringBuilder previousValue = valuesStack.pop();
StringBuilder newValue = new StringBuilder();
for (int i = 0; i < times; i++) {
newValue.append(previousValue);
}
valuesStack.peek().append(newValue);
} else {
valuesStack.peek().append(c);
}
}
return valuesStack.pop().toString();
}
}