Simple Java Solution beats 99%


  • 0
    M
    public int longestPalindrome(String s) {
        char[] c = s.toCharArray();
        int[] count = new int[128];
        int result = 0;
        boolean flag = false;
        for (int i : c) {
            count[i]++;
        }
        for (int i = 0; i < count.length; i++) {
            if (count[i] % 2 == 1) flag = true;
            result += count[i] / 2 * 2;
        }
        if (flag == true) result++;
        return result;
    }

  • 0
    M
    1. Count all the letters.
    2. If count of one character is greater than two, then it can be used as two digits in the palindrome.
    3. Use flag to see if there exists an extra character to be put in the middle of the palindrome.
    4. Return the sum.

Log in to reply
 

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