-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode-string.java
39 lines (33 loc) · 1.16 KB
/
decode-string.java
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
39
// Problem link - https://leetcode.com/problems/decode-string/
class Solution {
public String decodeString(String s) {
Stack<Character> stack = new Stack<>();
for(char c: s.toCharArray()){
if(c != ']'){
stack.push(c);
} else {
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty() && Character.isLetter(stack.peek())){
sb.insert(0, stack.pop());
}
String sub = sb.toString();
stack.pop();
sb = new StringBuilder();
while(!stack.isEmpty() && Character.isDigit(stack.peek())){
sb.insert(0, stack.pop());
}
int count = Integer.valueOf(sb.toString());
while(count > 0){
for(char ch: sub.toCharArray()){
stack.push(ch);
}
count--;
}
}
}
StringBuilder ans = new StringBuilder();
while(!stack.isEmpty())
ans.insert(0, stack.pop());
return ans.toString();
}
}