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
- CC 150 1.4 Palindrome Permutation
- 1.4 Palindrome Permutation
- Palindrome Permutation
- Palindrome Permutation
- Palindrome Permutation
- Leetcode: Palindrome Permutation
- *LeetCode-Palindrome Permutation
- [LeetCode 266]Palindrome Permutation
- 266 Palindrome Permutation
- [LeetCode266]Palindrome Permutation
- [LeetCode267]Palindrome Permutation II
- Leetcode - 266. Palindrome Permutation
- Leetcode266 Palindrome Permutation
- [Leetcode 266] Palindrome Permutation
- LeetCode 266. Palindrome Permutation
- Palindrome Permutation II
- 266. Palindrome Permutation
- Palindrome Permutation II
- Android PowerManager 之一 初识
- 自动监测内存泄漏
- C++的继承和java的继承
- Java之多线程机制-(1)
- hdu1024(动态规划+滚动数组优化)
- CC 150 1.4 Palindrome Permutation
- 文章标题
- Matlab中用fft作频谱后为什么要用fftshift
- htm表单提交给服务器&服务器接收浏览器的参数进行显示
- HDU 1863 最小生成树
- OpenGL版本与OpenGL扩展机制
- 实习感悟
- 三色球排序
- Python环境变量PYTHONPATH设置