409. 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.
his 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.

给定一组字符串,求能够组合出最长的回文串,分为两种情况:

  • 字符串内每个字符都为偶数个,例如:'abccba',出现的字符种类为3,这种毫无疑问最大的长度为2 * 3
  • 某个字符出现了基数次,例如abccccdd,组成的 长度为2*3 + 1
    代码:
public int longestPalindrome(String s) {
        if(s == null || s.length() == 0) return 0;
        HashSet<Character> hs = new HashSet<Character>();
        int count = 0;
        for(int i = 0; i < s.length(); i++)
        {
            if(hs.contains(s.charAt(i)))
            {
                hs.remove(s.charAt(i));
                count ++;
            }
            else
                hs.add(s.charAt(i));
        }
        if(!hs.isEmpty()) return count * 2 + 1;
        return count * 2;
    }

posted on 2017-11-02 09:35  Wanna_Go  阅读(151)  评论(0编辑  收藏  举报

导航