很高兴这道题很快的就做出来了,并且一次通过。
如果是偶数,那么除以2,再乘以2,如果字母数量存在奇数,是奇数那么 +1,else 不加一。
关键:存入dictionary:[a,1] [b,1] [c,4] [d,2]
c#答案代码如下:
public static int LongestPalindrome(string s)
{
int res = 0;
var dic =new Dictionary<char, int>();
for (int i = 0; i < s.Length; i++)
{
if (dic.ContainsKey(s[i]))
{
dic[s[i]]++;
}
else
{
dic[s[i]] = 1;
}
}
//[a,1] [b,1] [c,4] [d,2]
bool b = false;
foreach (var item in dic)
{
if (item.Value==1||item.Value%2!=0)
{
b = true;
}
res += item.Value / 2;
}
if (b)
{
res = res * 2 + 1;
}
else
{
res = res * 2;
}
return res;
}
public static void Main(string[] args)
{
string s = "abccccdd";
int c= LongestPalindrome(s);
Console.WriteLine(c);
Console.ReadKey();
}