[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;
    }
}
相關文章
相關標籤/搜索