您的位置:首页 > 其它

[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 };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: