[C#][LeetCode][Easy] 409. Longest Palindrome

心得

獲得字串並判斷字串內的字母能組成最長的回文大小為多少,例如傳入asdasdAAAvzxh則答案為9,字串為asdAvAdsa,其中v可替換成任意一位使用字母。

問題

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.

答案

public class Solution {
    public int LongestPalindrome(string s) {
        int ans = 0;
        int[] lower = new int[26];
        int[] upper = new int[26];
        foreach (var item in s)
        {
            if (item > 'Z')
            {
                lower[item - 'a']++;
            }
            else
            {
                upper[item - 'A']++;
            }

        }
        for (int i = 0; i < lower.Length; i++)
        {
            ans += lower[i] / 2;
            ans += upper[i] / 2;
        }

        ans = ans * 2;
        return ans < s.Length ? ans + 1 : ans;
    }
}

 



這裡的資訊對您有用嗎?歡迎斗內給我