-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path394. Decode String.java
More file actions
34 lines (34 loc) · 1.18 KB
/
Copy path394. Decode String.java
File metadata and controls
34 lines (34 loc) · 1.18 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
class Solution {
public String decodeString(String s) {
int index=0;
Deque<Integer> countStack = new ArrayDeque<>();
Deque<String> strStack = new ArrayDeque<>();
StringBuilder res = new StringBuilder();
while (index<s.length()){
char c = s.charAt(index);
if(Character.isDigit(c)){
int count=0;
while (index<s.length()&&Character.isDigit(s.charAt(index))){
count = count*10 + (s.charAt(index++) - '0');
}
countStack.push(count);
}else if (c == '['){
strStack.push(res.toString());
res = new StringBuilder();
index++;
}else if (c == ']'){
StringBuilder temp = new StringBuilder(strStack.pop());
int count=countStack.pop();
for (int n=0;n<count;n++){
temp.append(res);
}
res = temp;
index++;
}else{
res.append(s.charAt(index));
index++;
}
}
return res.toString();
}
}