409. Longest Palindrome (Easy)

https://leetcode.com/problems/longest-palindrome/

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

Solutions

class Solution {

    public int longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        Map<Character, Integer> occurrence = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!occurrence.containsKey(c)) {
                occurrence.put(c, 0);
            }

            occurrence.put(c, occurrence.get(s.charAt(i))+ 1);
        }

        int ans = 0;
        int extra = 0;
        for (Character c : occurrence.keySet()) {
            int count = occurrence.get(c);
            if (count % 2 == 0) {
                ans += count;
            } else {
                ans += count - 1;
                extra += 1;
            }
        }

        if (extra > 0) {
            ans += 1;
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 00:26:46

results matching ""

    No results matching ""