Given an array of Strings, find the frequency of occurrence of a particular character.
eg. Given array {"hon","bhig","zzz","hello"} and character 'h', the output is 3.
Here's how I solved it: Approach 1: Iterate through every string in the array, increment a counter every time that character occurs in the current String. Run time is O(n), where n is the cumulative length of all strings in the array.
Approach 2: This can be optimized using a HashMap; this is particularly helpful if the strings are repeated in the array. Here's what I did: take a HashMap where key = string and value = number of times that string occurs in the array. Put all strings in the given array into the HashMap along with their counts. Then iterate over each key-value pair in the HashMap, count the number of times the given character appears in the key(string) and increment it by its corresponding value in the HashMap.
My question is: Is there a better way to do this?
Here's the code:
NOTE: PLEASE READ THE ENTIRE ACCEPTED ANSWER.
public static int findFreq(String[] arr,char c) {
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=0;i<arr.length;i++) {
if(map.containsKey(arr[i]))
map.put(arr[i],map.get(arr[i])+1);
else
map.put(arr[i], 1);
}
int freq=0;
for(Entry<String,Integer> entr:map.entrySet()) {
String s = entr.getKey();
for(int i=0;i<s.length();i++) {
if(s.charAt(i)==c)
freq += entr.getValue();
}
}
return freq;
}