Java solution use a mark variable


  • 0
    Y
    class Solution {
        public boolean canPermutePalindrome(String s) {
            char[] arr = s.toCharArray();
            Arrays.sort(arr);
            int count = 0;
            int mark = -1;
            for(int i = 1 ; i < arr.length ; i++){
                if(count < -1){
                    return false;
                }
               if(arr[i] == arr[i-1]){
                   mark = (-1) * mark;
                   
               }
                else{
                    if(mark == -1){
                        count = count + mark;
                    }
                    mark = -1;
                }
            }
            if(count < 0 && mark == -1){
                
                return false;
            }
            return true;
        }
    }
    

    if one character appears even times, mark = 1, else mark =-1;
    the numbers of character which appears odd times can't be more than 1. At most, only one. So use a count variable to store how many character appears odd times.


Log in to reply
 

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