266. Palindrome Permutation

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容