LeetCode 409. 最长回文串(C、C++、python)


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

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

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

示例 1:

输入:
"abccccdd"

输出:
7

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

C

int longestPalindrome(char* s) 
{
    int n=strlen(s);
    int tmp[52]={0};
    for(int i=0;i<n;i++)
    {
        if(s[i]>='a' && s[i]<='z')
        {
            tmp[s[i]-'a']++;
        }
        else
        {
            tmp[s[i]-'A'+26]++;
        }
    }
    for(int i=0;i<52;i++)
    {
        if(1==tmp[i]%2)
        {
            n--;
        }
    }
    if(n==strlen(s))
    {
        return n;
    }
    else
    {
        return n+1;
    }
}

C++

class Solution {
public:
    int longestPalindrome(string s) 
    {
        int n=s.length();
        unordered_map<char,int> tmp;
        for(int i=0;i<n;i++)
        {
            tmp[s[i]]++;
        }
        unordered_map<char,int>::iterator it;
        for(it=tmp.begin();it!=tmp.end();it++)
        {
            if(it->second%2==1)
            {
                n--;
            }
        }
        if(n==s.length())
        {
            return n;
        }
        else
        {
            return n+1;
        }
    }
};

python

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        n=len(s)
        dic={}
        for i in range(n):
            if s[i] not in dic:
                dic[s[i]]=1
            else:
                dic[s[i]]+=1
        for key in dic:
            if 1==dic[key]%2:
                n-=1
        if n==len(s):
            return n
        else:
            return n+1
        

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/84886324
今日推荐