leetcode Solution for 451 problem
URL For Question: Sort Characters By Frequency
Solution With Comments(Explination)
package leetcode_code;
import java.util.HashMap;
import java.util.Map.Entry;
public class SortCharacterByName_421 {
public static void main(String[] args) {
String s = "tree";
charCounter(s);
}
public static String charCounter(String s) {
HashMap<Character, Integer> feqCounter =new HashMap<>();
// this loop gives count of character with count of character
// ex: {r=1, t=1, e=2}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (feqCounter.containsKey(c)) {
feqCounter.put(c, feqCounter.get(c) + 1);
} else {
feqCounter.put(c, 1);
}
}
return strngGenrtr(feqCounter);
}
//here we are combining all elements by appending
// EX:tree--eert(solution)
public static String strngGenrtr(HashMap<Character, Integer> feqCounter) {
StringBuilder br = new StringBuilder();
while (!feqCounter.isEmpty()) {
char maximun = getMax(feqCounter);
int count = feqCounter.get(maximun);
for (int i = 0; i < count; i++) {
br.append(maximun);
}
feqCounter.remove(maximun);
}
return br.toString();
}
//it will fetch max count of character element present
public static char getMax(HashMap<Character, Integer> feqCounter) {
int max = 0;
char key = '0';
for (Entry<Character, Integer> entry : feqCounter.entrySet()) {
if (entry.getValue() > max) {
key = entry.getKey();
max = entry.getValue();
}
}
return key;
}
}