CC 150 1.4 Palindrome Permutation

来源:互联网 发布:2017程序员看的书 编辑:程序博客网 时间:2024/06/05 04:45
Given a string , write a function to check if it is a permutation of a palindrome. 给定字符串,写方法检查是否是回文的排列;
https://www.interviewcake.com/question/java/permutation-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
原创粉丝点击