[leetcode] 266. Palindrome Permutation 解题报告

题目链接:https://leetcode.com/problems/palindrome-permutation/

Given a string, determine if a permutation of the string could form a palindrome.

For example,
"code" -> False, "aab" -> True, "carerac" -> True.

Hint:

  1. Consider the palindromes of odd vs even length. What difference do you notice?
  2. Count the frequency of each character.
  3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

思路:提示给了很明显的答案,如果所有的字符都出现偶数次,那么肯定可以回文.如果只有一个字符出现奇数次,肯定也可以回文.因此我们只要用一个hash表来记录,如果这个字符出现过了,则从hash表中删除掉.否则就加入hash表.最后表的长度为0或者为1,则可以回文.

今天facebook一面过了,还有一面就可以拿到intern offer了,在接下来的一两周之内我要全力以赴,所以开通了leetcode的会员,这是我人生中非常重要的时刻了,做好最充足的准备!求好运!

代码如下:

class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map<char, int> mp;
        for(int i = 0; i< s.size(); i++)
        {
            if(mp.find(s[i]) != mp.end())
                mp.erase(s[i]);
            else
                mp[s[i]] = 1;
        }
        if(mp.size() <= 1) return true;
        return false;
    }
};

你可能感兴趣的:(LeetCode,回文数)