Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
一刷
题解:
词频统计
public class Solution {
public boolean canPermutePalindrome(String s) {
int[] freq = new int[26*2];
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(ch <='z' && ch>='a') freq[ch - 'a']++;
else if(ch <='Z' && ch>='A') freq[ch - 'A' + 26]++;
}
int odd = 0;
for(int i=0; i<freq.length; i++){
if((freq[i]&1) == 1) odd++;
}
return odd<2;
}
}
或者用set,应该更快
二刷
sort
class Solution {
public boolean canPermutePalindrome(String s) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
int pos = 0;
boolean count = false;
while(pos<arr.length){
if(pos == arr.length-1) {
return !count;
}
else if(arr[pos] == arr[pos+1]) pos+=2;
else {
if(count) {
return false;
}
count = true;
pos++;
}
}
return true;
}
}