-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDecodeString.java
More file actions
29 lines (27 loc) · 1.11 KB
/
DecodeString.java
File metadata and controls
29 lines (27 loc) · 1.11 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
package com.dbc;
import java.util.Stack;
public class DecodeString {
public String decodeString(String s) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ']') {
StringBuilder subStr = new StringBuilder();
while (!stack.isEmpty() && !stack.peek().equals("[")) subStr.insert(0, stack.pop());
if (!stack.isEmpty()) {
stack.pop();
StringBuilder numStr = new StringBuilder();
while (!stack.isEmpty() && stack.peek().length() == 1 && Character.isDigit(stack.peek().charAt(0))) numStr.insert(0, stack.pop());
int num = Integer.parseInt(numStr.toString());
for (int j = 0; j < num; j++) stack.add(subStr.toString());
}
} else {
stack.add(Character.toString(s.charAt(i)));
}
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()) {
res.insert(0, stack.pop());
}
return res.toString();
}
}