451. Sort Characters By Frequency (leetcode) Get link Facebook X Pinterest Email Other Apps February 23, 2022 class Solution { public String frequencySort(String s) { HashMap 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); } public String strngGenrtr(HashMap 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(); } public char getMax(HashMap feqCounter) { int max = 0; char key = '0'; for (Map.Entry entry : feqCounter.entrySet()) { if (entry.getValue() > max) { key = entry.getKey(); max = entry.getValue(); } } return key; } } Click to Copy Get link Facebook X Pinterest Email Other Apps Comments
Comments
Post a Comment