【程序员面试金典】01.04. 回文排列

1.题目

给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。
回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。
回文串不一定是字典当中的单词。

示例1:

输入:"tactcoa"
输出:true(排列有"tacocat""atcocta",等等)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-permutation-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.题解

哈希,判断出现次数为奇数的字母个数是否大于一。
可以使用stl模板,或者自己建立数组哈希。

class Solution {
public:
    bool canPermutePalindrome(string s) {
        vector<int> hash(256, 0);
        for (auto c : s) {
            ++hash[c];
        }
        int cnt = 0;
        for (int i = 0; i < hash.size(); ++i) {
            if (hash[i] % 2 == 1) ++cnt;
        }
        return cnt <= 1;
    }
};

直接使用库中的bitset.

class Solution {
public:
    bool canPermutePalindrome(string s) {
        bitset<128> bits;
        for (char c : s) {
            bits.flip(c);
        }
        return bits.none() || bits.count() == 1;
    }
};

链接:https://leetcode-cn.com/problems/palindrome-permutation-lcci/solution/wei-yun-suan-shi-yong-c-bitset-4xing-dai-ma-jie-ju/

你可能感兴趣的:(#,程序员面试金典,OJ)