Skip to content

Commit e486400

Browse files
committed
Completed May 22
0 parents  commit e486400

File tree

5 files changed

+80
-0
lines changed

5 files changed

+80
-0
lines changed

.idea/.gitignore

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/misc.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/modules.xml

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

LeetCode.iml

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
</component>
11+
</module>

src/MayChallenges/May22.java

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package MayChallenges;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
/*
8+
May 22
9+
10+
Question: Sort Characters By Frequency
11+
Given a string, sort it in decreasing order based on the frequency of characters.
12+
13+
https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/537/week-4-may-22nd-may-28th/3337/
14+
*/
15+
16+
class May22 {
17+
static class Alphabet {
18+
char letter;
19+
int count;
20+
21+
Alphabet(char letter, int count) {
22+
this.letter = letter;
23+
this.count = count;
24+
}
25+
}
26+
27+
public String frequencySort(String s) {
28+
StringBuilder builder = new StringBuilder();
29+
HashMap<Character, Integer> hashMap = new HashMap<>();
30+
ArrayList<Alphabet> alphabets = new ArrayList<>();
31+
32+
for (int i = 0; i < s.length(); i++) {
33+
char letter = s.charAt(i);
34+
if (hashMap.containsKey(letter)) hashMap.put(letter, hashMap.get(letter) + 1);
35+
else hashMap.put(letter, 1);
36+
}
37+
38+
for(Map.Entry element: hashMap.entrySet())
39+
alphabets.add(new Alphabet((char) element.getKey(), (int) element.getValue()));
40+
41+
alphabets.sort((o1, o2) -> {
42+
if (o1.count != o2.count) return o2.count - o1.count;
43+
else return Character.toString(o1.letter).compareTo(Character.toString(o2.letter));
44+
});
45+
46+
for (Alphabet alphabet : alphabets) {
47+
for (int i = 0; i < alphabet.count; i++)
48+
builder.append(alphabet.letter);
49+
}
50+
51+
return builder.toString();
52+
}
53+
}

0 commit comments

Comments
 (0)