String Char Counts Using Collections:
package InterViewQuestions;
import java.util.HashMap;
import java.util.Map;
public class StringCharCountsUsingCollections {
//string = hemchandrraBhatt
//print number chars repeated
public static void main(String[] args) {
String str = "hemchandrabhatt";
HashMap<Character, Integer> mapCharCount = new HashMap<>();
char[] charArr = str.toCharArray();
for (char c : charArr) {
if (mapCharCount.containsKey(c)) {
mapCharCount.put(c, mapCharCount.get(c) + 1);
} else {
mapCharCount.put(c, 1);
}
}
//System.out.println(mapCharCount);
for (Map.Entry entry : mapCharCount.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
// Time complexity: O(n) where n is length of given string
//Auxiliary Space: O(n)
}
}