LeetCode 266. Palindrome Permutation(对称排列)

来源:互联网 发布:minitab 两组数据分析 编辑:程序博客网 时间:2024/05/01 16:09

原题网址: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:

  1. Consider the palindromes of odd vs even length. What difference do you notice?
  2. Count the frequency of each character.
  3. 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;    }}


0 0