-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDECODESTRING.java
More file actions
32 lines (32 loc) · 1.13 KB
/
DECODESTRING.java
File metadata and controls
32 lines (32 loc) · 1.13 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
class Solution {
public String decodeString(String str) {
Stack<Character> s = new Stack<>();
for (char c : str.toCharArray()) {
if (c == ']') {
StringBuilder decodedString = new StringBuilder();
while (!s.isEmpty() && s.peek() != '[') {
decodedString.insert(0, s.pop());
}
if (!s.isEmpty()) {
s.pop();
}
StringBuilder num = new StringBuilder();
while (!s.isEmpty() && Character.isDigit(s.peek())) {
num.insert(0, s.pop());
}
int numberOfTimes = Integer.parseInt(num.toString());
String repeated = decodedString.toString().repeat(numberOfTimes);
for (char t : repeated.toCharArray()) {
s.push(t);
}
} else {
s.push(c);
}
}
StringBuilder result = new StringBuilder();
while (!s.isEmpty()) {
result.append(s.pop());
}
return result.reverse().toString();
}
}