Skip to content

Commit 4a69541

Browse files
committed
Runtime: 12 ms (Top 83.68%) | Memory: 45.80 MB (Top 20.05%)
1 parent 7cd61c3 commit 4a69541

File tree

1 file changed

+32
-36
lines changed

1 file changed

+32
-36
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,41 @@
1+
// Runtime: 12 ms (Top 83.68%) | Memory: 45.80 MB (Top 20.05%)
2+
13
class Solution {
24
public String frequencySort(String s) {
3-
HashMap<Character,Integer> hm1=new HashMap<>();
4-
TreeMap<Integer,ArrayList<Character>> hm2=new TreeMap<>(Collections.reverseOrder());
5-
for(int i=0;i<s.length();i++)
6-
{
7-
char c=s.charAt(i);
8-
if(hm1.containsKey(c))
9-
{
10-
hm1.put(c,hm1.get(c) + 1);
11-
}
12-
else
13-
{
14-
hm1.put(c,1);
15-
}
5+
int len = s.length();
6+
HashMap<Integer,HashSet<Character>> map = new HashMap();
7+
HashMap<Character,Integer> freqMap = new HashMap();
8+
9+
for(int idx = 0;idx<len;idx++){
10+
char ch = s.charAt(idx);
11+
freqMap.put(ch,freqMap.getOrDefault(ch,0)+1);
1612
}
17-
for(char c : hm1.keySet())
18-
{
19-
if(hm2.containsKey(hm1.get(c)))
20-
{
21-
ArrayList<Character> temp=hm2.get(hm1.get(c));
22-
temp.add(c);
23-
hm2.put(hm1.get(c),temp);
24-
}
25-
else
26-
{
27-
ArrayList<Character> temp=new ArrayList<>();
28-
temp.add(c);
29-
hm2.put(hm1.get(c),temp);
30-
}
13+
14+
int maxFreq = 0 , minFreq = s.length();
15+
16+
for(char ch : freqMap.keySet()){
17+
HashSet<Character> set = map.getOrDefault(freqMap.get(ch),new HashSet());
18+
set.add(ch);
19+
map.put(freqMap.get(ch),set);
20+
maxFreq = Math.max(maxFreq , freqMap.get(ch));
21+
minFreq = Math.min(minFreq,freqMap.get(ch));
3122
}
32-
StringBuilder sb=new StringBuilder("");
33-
for(int x :hm2.keySet())
34-
{
35-
ArrayList<Character> temp=hm2.get(x);
36-
for(char c: temp)
37-
{
38-
for(int i=0;i<x;i++){
39-
sb.append(c);
23+
24+
StringBuilder ansStr = new StringBuilder();
25+
26+
for(int freq = maxFreq;freq>=minFreq;freq--){
27+
if(map.containsKey(freq)){
28+
HashSet<Character> set = map.get(freq);
29+
for(char ch : set){
30+
int temp = freq;
31+
while(temp>0){
32+
ansStr.append(ch);
33+
temp--;
34+
}
4035
}
4136
}
4237
}
43-
return sb.toString();
38+
39+
return ansStr.toString();
4440
}
4541
}

0 commit comments

Comments
 (0)