409. Longest Palindrome*

来源:互联网 发布:mac flash过期 编辑:程序博客网 时间:2024/05/18 13:48

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:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.
    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;    }
总结:注意两点,第一,最后如果hs中有多个元素,仍然只能取出来一个。第二,利用是否重复来决定该key是否可以组成回文数。



0 0