-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecodeString.java
More file actions
33 lines (29 loc) · 1.01 KB
/
decodeString.java
File metadata and controls
33 lines (29 loc) · 1.01 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
class Solution {
public String decodeString(String s) {
Stack<String> stack= new Stack<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=']'){
stack.push(String.valueOf(s.charAt(i)));
}
else{
StringBuilder substr=new StringBuilder();
while(!stack.peek().equals("[")){
substr.insert(0,stack.pop());
}
stack.pop();
StringBuilder k=new StringBuilder();
while(!stack.isEmpty() && Character.isDigit(stack.peek().charAt(0))){
k.insert(0,stack.pop());
}
int count=Integer.parseInt(k.toString());
String repeatedstr=substr.toString().repeat(count);
stack.push(repeatedstr);
}
}
StringBuilder res= new StringBuilder();
while(!stack.isEmpty()){
res.insert(0,stack.pop());
}
return res.toString();
}
}