I got a java question asked in an interview. Print distinct characters in a string and print stars (*) under each character which shows how many times the character repeated in that string.
For eg: my string is "GOOGLE", then the output should be
G O L E
* * * *
* *
I tried in java and I was able to create a HashMap which will store the Character and Number of repetitions in the string. But the HashMap is not based on the Insertion order of the string. Also I don't know what should be my next step. Can someone help me? Thanks in advance
public void myFunction(String str) {
int length = str.length();
HashMap<Character, Integer> hm = new HashMap<>();
for(int i=0;i<length;i++){
char ch = str.charAt(i);
if(hm.containsKey(ch)){
hm.put(ch, hm.get(ch)+1);
}
else {
hm.put(ch, 1);
}
}
System.out.println(hm);
}
OUTPUT - Enter a String:
GOOGLE
{E=1, G=2, L=1, O=2}