straightforward java solution


  • 0
    F

    first solution, using array:

        public int longestPalindrome(String s) {
            int[] count = new int[52];
            for (char c : s.toCharArray()) {
                if (Character.isLowerCase(c)) {
                    count[c - 'a']++;
                } else {
                    count[c - 'A' + 26]++;
                }
            }
            int result = 0;
            boolean flag = false;
            for (int i : count) {
                if (i % 2 != 0) {
                    result += i - 1;
                    flag = true;
                } else {
                    result += i;
                }
            }
            if (flag) {
                result++;
            }
            return result;
        }
    

    second solution, using hashmap:

        public int longestPalindrome2(String s) {
            HashMap<Character, Integer> hashMap = new HashMap<>();
            for (char c : s.toCharArray()) {
                hashMap.put(c, hashMap.getOrDefault(c, 0) + 1);
            }
            int result = 0;
            boolean flag = false;
            for (Integer num : hashMap.values()) {
                if (num % 2 != 0) {
                    result += num - 1;
                    flag = true;
                } else {
                    result += num;
                }
            }
            if (flag) {
                result++;
            }
            return result;
        }
    

Log in to reply
 

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