leettcode--最長迴文串

1 \ 題目描述

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

2、 解題思路

對於這種固定數組的,我們可以建立一個數組,用來存儲每個字母對應的個數記錄下來,然後循環數組,當出現第一個奇數個的時候,多出來的一個可以放在中間的位置,而剩下的多出來的就不能在算,也就是要取偶數個。

 

3、 代碼(CPP)

class Solution {
public:
    int longestPalindrome(string s) {
            int strlen=s.length();
    int ans=0;
    bool flag=false;
    // doublt pointer??
    int nums[52]={0}; //分別對應了a-z A-Z

    for(int i=0;i<s.length();i++){
        if (s[i]>='a' and s[i]<='z'){
                nums[s[i]-'a']+=1;
        }else if (s[i]>='A' and s[i]<='Z'){
                nums[s[i]-'A'+26]+= 1;


        }

    }
    for(int i =0;i<52;i++){
        if(nums[i]%2==0){
            ans += nums[i];
        }else if(!flag){
            if (nums[i]==1){
                ans += 1;
            }else{
            ans += nums[i];
            }
            flag = true;
        }else{
            ans += nums[i]-1;
        }
 


    }
    return ans;
    }
};

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章