CC-8 : Check if characters of the String occur with the same frequency.
Description:
Given input String str, check if all characters of str occur with the same frequency.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| str="aazzecc"; | The characters of the String do *not* occur at equal frequency |
| str="aazzcc"; | The characters of the String occur at equal frequency |
| str=" azzccccdddd"; | The characters of the String do *not* occur at equal frequency |
Pseudocode:
| The java method should accept following input parameters: str (String). |
| Initialize a variable chrFreqMap of type HashMap |
| Iterate through str using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches str.length()-1:
If chrFreqMap does not contain key equal to str.charAt(idx):
Add key str.charAt(idx)and add value 1 to chrFreqMap.
If chrFreqMap contains key equal to str.charAt(idx):
Add key str.charAt(idx)and add value equal to current value of key str.charAt(idx), incremented by 1 to chrFreqMap.
|
| After completion of above loop, chrFreqMap contains all characters of str as keys and the counts of these characters as values. |
| Using an iterator, iterate through all keys and values of chrFreqMap, if all values are the same, return true from the program, else return false. |
Code:
public boolean hashMapSameFreq(String str) throws Exception{
HashMap<Character,Integer> chrFreqMap=new HashMap<Character, Integer>();
for (int idx=0; idx < str.length(); idx++) {
chrFreqMap.put(str.charAt(idx), chrFreqMap.getOrDefault(str.charAt(idx),0)+1);
}
Iterator<Integer> itr=chrFreqMap.values().iterator();
int frstChrCnt=0; int idx=0; int freq=0;
while (itr.hasNext()) {
freq=(Integer)itr.next().intValue();
if (idx==0) {
frstChrCnt=freq;
idx++;
}else {
if (freq != frstChrCnt) {
return false;
}
}
}
return true;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |