[Leetcode]Longest Palindrome

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.c++

This is case sensitive, for example "Aa" is not considered a palindrome here.ide

Note:
Assume the length of given string will not exceed 1,010.ui

Example:code

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
  1. 解题思路string

咱们发现结果其实就是字符的偶数个数+是否有单一的字符,若是有就加1(把单一字符放在回文中间),若是没有就加0;
字母区分大小写,int[] map=new int['z'-'A'+1];
2.代码it

public class Solution {
    public int longestPalindrome(String s) {
        if(s.length()==0||s==null) return 0;
        int[] map=new int['z'-'A'+1];
        int count=0;
        int hasOdd=0;
        for(int i=0;i<s.length();i++){
            map[s.charAt(i)-'A']++;
        }
        for(char c='A';c<='z';c++){
            if((map[c-'A'] & 1)==1){
                hasOdd=1;
                count+=(map[c-'A']-1);
            }
            else 
                count+=map[c-'A'];
        }
        return count+hasOdd;
    }
}
相关文章
相关标签/搜索