leetcode409.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.

輸入一個字符串,計算用這個字符串中的值構成一個最長回數的長度是多少。ide

思路和代碼

這是一道easy難度的題目,可是一次性寫對也有挑戰。直觀來看,咱們馬上就能想到統計字符串中每一個字符出現的次數,若是該字符出現次數爲偶數,則字符必定存在於回數中。可是咱們忽略了一點,即若是字符中存在一個額外的單個字符位於中間,該字符串也能構成回數,如aabaa。這個細節須要注意。
下面是O(N)時間的實現:ui

public int longestPalindrome(String s) {
        int[] count = new int[52];
        int max = 0;
        for(char c : s.toCharArray()) {
            if(c>='a' && c<='z'){
                count[c-'a']++;
                if(count[c-'a'] % 2 == 0) {
                    max +=2;
                }
            }
            
            if(c>='A' && c<='Z'){
                count[c-'A' + 26]++;
                if(count[c-'A'+26] % 2 == 0) {
                    max += 2;
                }
            }
        }
        
        if(max < s.length()) {
            max++;
        }
        return max;
    }
相關文章
相關標籤/搜索