Wednesday, December 28, 2016

Leetcode/G家--409.Longest Palindrome(HashMap)

 409. Longest Palindrome(HashMap)
  • Difficulty: 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.

Input:
"abccccdd"

Output:
7
思路:将每个字母的数目存入map,偶数全加入结果,奇数加入num-1,最后奇数补1(如果存在)
关键字: HashMap

public class Solution {
    public int longestPalindrome(String s) {
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i=0;i<s.length();i++){
            if(map.get(s.charAt(i))==null){
                map.put(s.charAt(i),1);
            }else{
                map.put(s.charAt(i),map.get(s.charAt(i))+1);
            }
        }
        int even = 0,odd= 0,single=0;
        for(Character key:map.keySet()){
            if(map.get(key)%2==0){ even += map.get(key);}
            else{ 
                single = 1;
                odd += map.get(key)-1;
            }
        }
        return even+odd+single;
    }
}

No comments:

Post a Comment