CC 150 1.4 Palindrome Permutation

Given a string , write a function to check if it is a permutation of a palindrome. 给定字符串,写方法检查是否是回文的排列;
回文:单词或短语,正序和倒叙都是相同的;
比如:
输入:Tact Coa
输出:True(permutations: "taco cat", "atco cta", etc.)

思路:
找到每个char的频率。
1 如果字符串长度为偶数, 必须所有的字符频次都是偶数;
2 如果字符串长度为奇数,必须只有一个字符词频是奇数;

举例: tactcoapapa 是permutation of palindrome, 因为:有2个t,4个a,2个c,2个p,1个0(中心点) 
  • "civic" should return true
  • "ivicc" should return true
  • "civil" should return false
  • "livci" should return false

public static bool IsPermutationOfPalindrome(string phrase)
        {
            if (string.IsNullOrEmpty(phrase))
                return false;

            //统计每个char的出现频率
            char[] strArr = phrase.ToCharArray();
            Dictionary<char, int> charFrequency = new Dictionary<char, int>();
            for (int i = 0; i < strArr.Length; i++)
            {
                char charVal = strArr[i];
                if (charFrequency.ContainsKey(charVal))
                {
                    charFrequency[charVal] += 1;
                }
                else
                {
                    charFrequency.Add(charVal, 1);
                }
            }

            //长度为奇数,只有一个是奇数,其他是偶数;
            if (phrase.Length % 2 != 0)
            {
                int oddFrequency = 0;
                foreach (var tmp in charFrequency.Values)
                {
                    if (tmp % 2 != 0)
                        oddFrequency++;
                }
                if (oddFrequency == 1)
                    return true;
                else
                    return false;
            }
            else//长度为偶数,全都是偶数;
            {
                foreach (var tmp in charFrequency.Values)
                {
                    if (tmp % 2 != 0)
                        return false;
                }
                return true;
            }

        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值