-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathDecodeString.java
31 lines (29 loc) · 962 Bytes
/
DecodeString.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
class DecodeString {
public String decodeString(String s) {
Stack<Integer> freqStack = new Stack<>();
Stack<StringBuilder> strStack = new Stack<>();
StringBuilder currStr = new StringBuilder();
int k =0;
for(char c : s.toCharArray()){
if(Character.isDigit(c)){
k = k*10 + (c-'0');
} else if (Character.isLetter(c)){
currStr.append(c);
} else if(c == '['){
freqStack.push(k);
strStack.push(currStr);
k =0;
currStr = new StringBuilder();
} else if(c == ']'){
StringBuilder temp = currStr;
int freq = freqStack.pop();
currStr = strStack.pop();
while(freq-->0){
currStr.append(temp);
}
k = 0;
}
}
return currStr.toString();
}
}