05 August 2008
字符串重新排列后是否能够形成回文
奇数字符不超过1个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean canPermutePalindrome(String s) {
if (s == null || s.length() == 0) {
return false;
}
int[] chars = new int[128];
for (char c : s.toCharArray()) {
chars[(int) c]++;
}
int count = 0;
for (int i : chars) {
if (i % 2 == 1) {
count++;
}
}
if (count > 1) {
return false;
}
return true;
}
不用counter
set.size()==0 corresponds to the situation when there are even number of any character in the string, and
set.size()==1 corresponsds to the fact that there are even number of any character except one.
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public boolean canPermutePalindrome(String s) {
Set<Character> set=new HashSet<Character>();
for(int i=0; i<s.length(); ++i){
if (!set.contains(s.charAt(i)))
set.add(s.charAt(i));
else
set.remove(s.charAt(i));
}
return set.size()==0 || set.size()==1;
}
}