-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathPalindromePermutation.java
More file actions
32 lines (28 loc) · 975 Bytes
/
PalindromePermutation.java
File metadata and controls
32 lines (28 loc) · 975 Bytes
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
// https://leetcode.com/problems/palindrome-permutation
// T: O(|s|)
// S: O(|s|)
import java.util.HashMap;
import java.util.Map;
public class PalindromePermutation {
public boolean canPermutePalindrome(String s) {
final Map<Character, Integer> frequencies = getCharacterFrequencies(s);
return getNumberOfOddChars(frequencies) <= 1;
}
private static Map<Character, Integer> getCharacterFrequencies(String string) {
final Map<Character, Integer> result = new HashMap<>();
for (int i = 0 ; i < string.length() ; i++) {
final char c = string.charAt(i);
result.put(c, result.getOrDefault(c, 0) + 1);
}
return result;
}
private static int getNumberOfOddChars(Map<Character, Integer> frequencies) {
int result = 0;
for (int freq : frequencies.values()) {
if (freq % 2 == 1) {
result++;
}
}
return result;
}
}