C#LeetCode刷题之#409-最长回文串(Longest Palindrome)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82709818

问题

给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。

注意:假设字符串的长度不会超过 1010。

输入:"abccccdd"

输出:7

解释:我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。


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.

Input:"abccccdd"

Output:7

Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.


示例

public class Program
{

    public static void Main(string[] args)
    {
        var s = "abccccdd";

        var res = LongestPalindrome(s);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int LongestPalindrome(string s)
    {
        var res = 0;
        var odd = false;
        var dic = new Dictionary<char, int>();
        foreach (var c in s)
        {
            if (dic.ContainsKey(c))
            {
                dic[c]++;
            }
            else
            {
                dic[c] = 1;
            }
        }

        foreach (var item in dic)
        {
            res += item.Value;
            if (item.Value % 2 == 1)
            {
                res -= 1;
                odd = true;
            }
        }
        return odd ? res + 1 : res;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

7

分析:

显而易见,以上算法的时间复杂度为: O(n)

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82709818