I got this problem in Amazon interview.
Given have a String in Java as input 3[a]2[bc]
write a function to decode it so the output should be as "**aaabcbc**
"
Input 3[a]2[bc] -> aaabcbc
Input 3[2[a]]4[b] -> aaaaabbbb
Invalid Input 3[4] `enter code here`
Invalid Input a[3]
I have tried the following approach but is not correct as it doesn't address nested elements
String test = "3[a]2[b]5[b]";
Map<Character, Integer> map = new HashMap<>();
char[] characters = test.toCharArray();
for (int i = 0; i < characters.length-1; i++) {
if(characters[i]=='['){
if(map.containsKey(characters[i+1])){
int count = map.get(characters[i+1]);
map.put(characters[i+1], Character.getNumericValue(characters[i-1])+count);
}else{
map.put(characters[i+1], Character.getNumericValue(characters[i-1]));
}
}
}
for (Map.Entry<Character, Integer> c : map.entrySet()) {
for (int i = 0; i < c.getValue(); i++) {
System.out.printf("%s",c.getKey());
}
}
What is the correct solution to this?
is it possible to use encapsulation class to decode this problem, if you observe the problem carefully its in the format, can we convert this to object of decoder class. 2[...]3[...]4[...]
class Decoder{
private int count;// digit example 2[a]3[bc]4[d] the count value will be 2,3,4
private String data; // example a,bc,d
private Decoder decoder; // for nested values example 3[2[a]] in this case decoder will be 2[a]
}