-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path394. Decode String
38 lines (35 loc) · 1.18 KB
/
394. Decode String
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
class Solution {
public String decodeString(String s) {
Stack<Character> stack = new Stack<>();
for(char ch : s.toCharArray()){
if(ch != ']'){
stack.push(ch);
}else{
//get the sub string
StringBuilder sb = new StringBuilder();
while(stack.peek() != '['){
sb.append(stack.pop());
}
//remove the '[' character
stack.pop();
//get the number
int k = 0;
int base = 1;
while(!stack.isEmpty() && Character.isDigit(stack.peek())){
k = (stack.pop() - '0') * base + k;
base *= 10;
}
//put back the substring in stack k times
while(k-- > 0){
for(int i=sb.length()-1; i>=0; i--){
stack.push(sb.charAt(i));
}
}
}
}
char[] result = new char[stack.size()];
for(int i=stack.size()-1;i>=0;i--)
result[i] = stack.pop();
return new String(result);
}
}