|
3 | 3 | import java.util.HashMap;
|
4 | 4 | import java.util.Map;
|
5 | 5 |
|
6 |
| -/**Given a string, determine if a permutation of the string could form a palindrome. |
7 |
| -
|
8 |
| - For example, |
9 |
| - "code" -> False, "aab" -> True, "carerac" -> True. |
10 |
| -
|
11 |
| - Hint: |
12 |
| -
|
13 |
| - Consider the palindromes of odd vs even length. What difference do you notice? |
14 |
| - Count the frequency of each character. |
15 |
| - If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?*/ |
16 | 6 | public class _266 {
|
17 | 7 |
|
18 |
| - public boolean canPermutePalindrome(String s) { |
19 |
| - |
20 |
| - char[] chars = s.toCharArray(); |
21 |
| - Map<Character, Integer> map = new HashMap<Character, Integer>(); |
22 |
| - for (char c : chars) { |
23 |
| - if (!map.containsKey(c)) { |
24 |
| - map.put(c, 1); |
25 |
| - } else { |
26 |
| - map.put(c, map.get(c) + 1); |
| 8 | + public static class Solution1 { |
| 9 | + public boolean canPermutePalindrome(String s) { |
| 10 | + |
| 11 | + char[] chars = s.toCharArray(); |
| 12 | + Map<Character, Integer> map = new HashMap<>(); |
| 13 | + for (char c : chars) { |
| 14 | + if (!map.containsKey(c)) { |
| 15 | + map.put(c, 1); |
| 16 | + } else { |
| 17 | + map.put(c, map.get(c) + 1); |
| 18 | + } |
27 | 19 | }
|
28 |
| - } |
29 |
| - int evenCount = 0; |
30 |
| - for (Map.Entry<Character, Integer> e : map.entrySet()) { |
31 |
| - if (e.getValue() % 2 != 0) { |
32 |
| - evenCount++; |
33 |
| - } |
34 |
| - if (evenCount > 1) { |
35 |
| - return false; |
| 20 | + int evenCount = 0; |
| 21 | + for (Map.Entry<Character, Integer> e : map.entrySet()) { |
| 22 | + if (e.getValue() % 2 != 0) { |
| 23 | + evenCount++; |
| 24 | + } |
| 25 | + if (evenCount > 1) { |
| 26 | + return false; |
| 27 | + } |
36 | 28 | }
|
| 29 | + return true; |
37 | 30 | }
|
38 |
| - return true; |
39 |
| - |
40 | 31 | }
|
41 | 32 |
|
42 | 33 | }
|
0 commit comments