Java AC 8 lines


  • 6
    W
    public class Solution {
        public boolean canPermutePalindrome(String s) {
            char[] A = new char[256];
            int count=0;
            for(int i=0; i<s.length(); i++){
                if(A[s.charAt(i)]>0)A[s.charAt(i)]--;
                else A[s.charAt(i)]++;
            }
            for(int i=0; i<256; i++){
                if(A[i]!=0)count++;
            }
            return count<=1;
        }
    }

  • 10
    A

    I think we can do it without scanning char[] A at last.

    public boolean canPermutePalindrome(String s) {
        char[] A = new char[256];
        int count=0;
        for(int i=0; i<s.length(); i++){
            if(A[s.charAt(i)]>0) {
                A[s.charAt(i)]--;
                count--;
            } else {
                A[s.charAt(i)]++;
                count++;
            }
        }
        return count<=1;
    }

  • 0
    J

    Kinda have the same idea but a little bit trivial

    public boolean canPermutePalindrome(String s) {
    		int odd = 0;
    		int[] arr = new int[256];
    		for(char c:s.toCharArray())
    			arr[c]++;
    		for(int x:arr) {
    			if(x%2!=0) { //No worry about even. We only care about how many odds.
    				odd++;
    				if(odd>1) //Should only have one odd.
    					return false;
    			}
    		}
    		return true;
        }

  • 0
    C

    @airwindow Agree with you. Also, I don't know why using char[] here. I think we can use boolean[] to be more concise and understandable.

    public boolean canPermutePalindrome(String s) {
        if(s==null) return false;
        if(s.length()<=1) return true;
        boolean[] map = new boolean[256];
        int count=0;
        for(int i=0; i<s.length(); i++){
            char ch = s.charAt(i);
            if(!map[ch]) count++;
            else count--;
            map[ch] = !map[ch];
        }
        return count<=1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.