-
Notifications
You must be signed in to change notification settings - Fork 5
/
SortCharactersByFrequency.java
47 lines (44 loc) · 1.43 KB
/
SortCharactersByFrequency.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Problem Statement:
Given a string, sort it in decreasing order based on the frequency of characters.
Problem Link:
Sort Characters By Frequency: https://leetcode.com/problems/sort-characters-by-frequency/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/SortCharactersByFrequency.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
class Frequency{
char c;
int i;
}
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap<>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0)+1);
}
List<Frequency> list = new ArrayList<>();
for(Map.Entry entry: map.entrySet()){
Frequency f = new Frequency();
f.c = (Character)entry.getKey();
f.i = (Integer)entry.getValue();
list.add(f);
}
Collections.sort(list, new Comparator<Frequency>(){
public int compare(Frequency f1, Frequency f2){
return f2.i - f1.i;
}
});
StringBuilder sb = new StringBuilder();
for(Frequency f: list){
for(int i=0;i<f.i;i++)
sb.append(f.c);
}
return sb.toString();
}
}