[Leetcode 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.


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 cmaps = new HashMap<>();
        int len = s.length();
        if(len<=1) return true;
        for(int i =0;i=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;
    }






你可能感兴趣的:(Leetcode,Java,Web,leetcode,HashMap,bit,manipulation)