卖萌的弱渣

I am stupid, I am hungry.

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.

Solution

  • Java
(Longest-Palindrome.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
    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))){
                count++;
                hs.remove(s.charAt(i));
            }
            else
                hs.add(s.charAt(i));
        }
        if(!hs.isEmpty()) return 2*count+1;
        else return 2*count;
    }
}