原题网址:https://leetcode.com/problems/palindrome-permutation/
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?
方法:统计各个字符的频率。
public class Solution {
public boolean canPermutePalindrome(String s) {
int[] f = new int[256];
char[] sa = s.toCharArray();
for(int i=0; i<sa.length; i++) f[sa[i]] ++;
int even = 0, odd = 0;
for(int i=0; i<f.length; i++) {
if ((f[i] & 1) == 0) even ++; else odd ++;
}
if ((sa.length & 1) == 0) {
return odd == 0;
} else {
return odd == 1;
}
}
}
可以进一步优化如下:
public class Solution {
public boolean canPermutePalindrome(String s) {
char[] sa = s.toCharArray();
int[] f = new int[256];
for(int i=0; i<sa.length; i++) f[sa[i]] ++;
boolean single = false;
for(int i=0; i<f.length; i++) {
if (f[i] % 2 == 1) {
if (!single) single = true; else return false;
}
}
return true;
}
}