[LeetCode] Palindrome Permutation
2015-08-21 17:41
169 查看
Problem Description:
Given a string, determine if a permutation of the string could form a palindrome.
For example,
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Just check there are no more than 2 characters that appear an odd number of times in the string.
My C++ code using an array as a hash map is as follows.
BTW, Stefan has posted many nice solutions here, including the following one that uses bitset.
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"-> False,
"aab"-> True,
"carerac"-> True.
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Just check there are no more than 2 characters that appear an odd number of times in the string.
My C++ code using an array as a hash map is as follows.
class Solution { public: bool canPermutePalindrome(string s) { int odd = 0, counts[256] = {0}; for (char c : s) odd += ++counts[c] & 1 ? 1 : -1; return odd <= 1; } };
BTW, Stefan has posted many nice solutions here, including the following one that uses bitset.
class Solution { public: bool canPermutePalindrome(string s) { bitset<256> b; for (char c : s) b.flip(c); return b.count() < 2; } };
相关文章推荐
- 供应紫外线杀菌器
- 对于异常的总结
- 约会计划
- 多线程应用(五)——线程操作函数
- ETL拉链算法汇总大全
- BZOJ2002: [Hnoi2010]Bounce 弹飞绵羊
- Flume学习(五):Flume Channel Selectors使用
- iOS 怎么自定制推送声音呢?(APP运行时和APP进入后台时)
- 【vim】插件管理及代码智能提示与补全环境的配置
- 聚集索引和非聚集索引速度对比
- Service层的抽象和实现
- Android:实现点击AlertDialog上按钮时不关闭对话框
- 引入Controller
- Java反射机制学习笔记
- mysql带参存储过程
- Container With Most Water
- 重载与覆盖
- BZOJ 3669 魔法森林 LCT
- OutMan——单例模式、代理模式以及iOS沙盒(sandbox)机制
- tomcat部署javaweb项目的三种方式