Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"
-> False, "aab"
-> True, "carerac"
-> True.
Solution1 - Hashtable, store number of each character's appearance. Palindrome should have at most one character appear odd times. otherwise it should not be palindrome.
public boolean canPermutePalindrome(String s) {
Map<Character, Integer> cmaps = new HashMap<>();
int len = s.length();
if(len<=1) return true;
for(int i =0;i<len;i++) {
char tmp = s.charAt(i);
if(cmaps.containsKey(tmp)) {
cmaps.put(tmp, cmaps.get(tmp)+1);
}else {
cmaps.put(tmp, 1);
}
}
int odd = 0;
for(char c: cmaps.keySet()) {
if(cmaps.get(c)%2 ==0) {
continue;
}else {
if(++odd>=2) return false;
}
}
return true;
}
Solution 2: similar with first one, we can use array with length 256 and XOR operation to determine whether has odd times character more than 1.
public boolean canPermutePalindrome(String s) {
int[] carray = new int[256];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(char c: s.toCharArray()) {
carray[c]^=1;
min = Math.min(min, c);
max = Math.max(max, c);
}
int sum = 0;
for(int i=min;i<=max;i++) {
sum +=carray[i];
}
return sum<=1;
}