Java 0ms solution using sorting


  • 0
    K
    public class Solution {
        
        public boolean canPermutePalindrome(String s) {
            if (s == null) {
                return true;
            }
            int l = s.length();
            if (l == 0) {
                return true;
            }
            if (l == 1) {
                return true;
            }
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            int count = 1;
            boolean flag = false;
            int i = 0;
            while (true) {
                if (chars[i] != chars[i + 1]) {
                    if (count % 2 != 0) {
                        if (flag) {
                            return false;
                        } else {
                            flag = true;
                        }
                    }
                    count = 1;
                } else {
                    count++;
                }
                i++;
                if (i == l - 1) break;
            }
            if (count % 2 != 0) {
                if (flag) {
                    return false;
                }
            }
            return true;
        }
    }
    

    This code runs in 0 ms. The key logic is there will be only 1 character that will repeat odd times. All other will repeat even number of times. Taking this into consideration we can reasonable reduce the time and space.


Log in to reply
 

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