congr / world

2 stars 1 forks source link

LeetCode : 409. Longest Palindrome #438

Closed congr closed 5 years ago

congr commented 5 years ago

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

image

congr commented 5 years ago
class Solution {
    public int longestPalindrome(String s) {
        char[] ch = s.toCharArray();
        Map<Character, Integer> map = new HashMap();

        for (char c : ch) map.merge(c, 1, Integer::sum);    

        int longest = 0;
        for (int n : map.values())  // {a=2, b=5, c=2, d=3, e=3}
            longest += (n/2) * 2;

        return (s.length() > longest) ? longest+1 : longest;
    }
}