[LeetCode 266]Palindrome Permutation
2015-10-20 21:58
176 查看
回文序列(回文结构)
如果一个序列的逆序列与原序列相同,则这个序列为回文序列或有回文结构。比如“1235321”。
如何判断回文结构:
最多只有一个字符的个数为奇数个,其余均为偶数个。
leetcode上有个相关题目:
Problem Description:
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?
网上有两种解答:
第一种C++
1 class Solution {
2 public:
3 bool canPermutePalindrome(string s) {
4 int odd = 0, counts[256] = {0};
5 for (char c : s)
6 odd += ++counts[c] & 1 ? 1 : -1;
7 return odd <= 1;
8 }
9 };
第二种采用C++的bitset
1 class Solution {
2 public:
3 bool canPermutePalindrome(string s) {
4 bitset<256> b;
5 for (char c : s) b.flip(c);
6 return b.count() < 2;
7 }
8 };
如果一个序列的逆序列与原序列相同,则这个序列为回文序列或有回文结构。比如“1235321”。
如何判断回文结构:
最多只有一个字符的个数为奇数个,其余均为偶数个。
leetcode上有个相关题目:
Problem Description:
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?
网上有两种解答:
第一种C++
1 class Solution {
2 public:
3 bool canPermutePalindrome(string s) {
4 int odd = 0, counts[256] = {0};
5 for (char c : s)
6 odd += ++counts[c] & 1 ? 1 : -1;
7 return odd <= 1;
8 }
9 };
第二种采用C++的bitset
1 class Solution {
2 public:
3 bool canPermutePalindrome(string s) {
4 bitset<256> b;
5 for (char c : s) b.flip(c);
6 return b.count() < 2;
7 }
8 };
相关文章推荐
- 启动新的Activity
- 贝叶斯
- OpenStack: Storage 组件 Swift 和 Cinder(转)
- 神经网络(1)--Non-linear hypotheses,为什么我们要学习神经网络这种算法来处理non-linear hypotheses
- 《需求工程——软件建模与分析》读后感之二
- Java Executor 框架
- Window - 浏览器对象模型
- Hadoop 2.0中单点故障解决方案总结
- iOS为UIView添加虚线边框
- ClassLoader的源码分析
- Java Executor 框架
- 自信
- Android开发中无处不在的设计模式——观察者模式
- mysql与oracle转换遇到小问题 关键字的处理
- Struts2-输入验证
- 队列的基本操作2
- Django Manager
- 字符串加密以及动手动脑截图
- Eat Style --proposed by Chongyang Bai
- c++11并发机制