Easy Understand Java Solution with Explanation - 13ms

  • 0

    The basic rule for palindrome is that there can only be one or zero odd frequency letter. Like aabaa which b is the only odd frequency number. Or aabbbaa, aabbbbbaa, aaaa... The string like aabbbcccaa will never be a palindrome. So if there is equal or fewer than one odd frequency letter, we return the string's length directly. If there is more than one odd frequency letter, we return string.length() - (odd frequency - 1) which is string.length() - odd + 1.

    public int longestPalindrome(String s) {
            char[] letters = s.toCharArray();
            int odd = 0;
            int[] map = new int[128];
            for (int i = 0; i < letters.length; ++i) {
                if (map[letters[i]] % 2 != 0)
            return odd <= 1 ? s.length() : s.length() - odd + 1;

Log in to reply

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