-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path266. Palindrome Permutation.java
executable file
·86 lines (73 loc) · 2.31 KB
/
266. Palindrome Permutation.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
E
tags: Hash Table
time: O(n)
space: O(n)
给String, 看permutation是否能是palindrome
#### Hash, or ASCII array
- count char occurrance
- 只可以接受一个odd # appearance.
- 考虑所有 256 ASCII code, 如果还要拓展, 就用HashMap<Character, Integer>
- 注意, 不能assume lower case letter. 应该至少是所有ASCII code
```
/*
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Tags: Hash Table
Similar Problems: (M) Longest Palindromic Substring, (E) Valid Anagram, (M) Palindrome Permutation II
*/
/*
- count char freq
- only have <1 odd char, and the rest are even freq
- LeetCode. Made assumption on ASCII code, so use int[256]
*/
class Solution {
public boolean canPermutePalindrome(String s) {
if (s == null || s.length() == 0) return false;
int[] chars = new int[256];
for (char c : s.toCharArray()) chars[c]++;
int countOdd = 0;
for (int i = 0; i < chars.length; i++) {
countOdd += chars[i] % 2;
if (countOdd > 1) return false;
}
return true;
}
}
/*
Add each char into map.
Count if odd > 1, false
Note: Iterate HashMap
HashMap.Entry<String, Integer> entry : map.entrySet()
*/
public class Solution {
public boolean canPermutePalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < s.length(); i++) {
String str = s.charAt(i) + "";
if (!map.containsKey(str)) {
map.put(str, 1);
} else {
map.put(str, map.get(str) + 1);
}
}//ENd for
int countOdd = 0;
for (HashMap.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() % 2 == 1) {
countOdd++;
}
if (countOdd > 1) {
return false;
}
}//END for
return true;
}
}
```