[LeetCode266]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:

    *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?

Hide Company Tags Google Uber
Hide Tags Hash Table
Hide Similar Problems (M) Longest Palindromic Substring (E) Valid Anagram (M) Palindrome Permutation II

通过观察,如果s是个even string,则要为Palindrome就不能有odd frequency的char, 如果s是 odd 则可以有一个odd frequency,所以总的来说至多可以有一个odd frequency 的char。

利用一个int 统计到底有多少个odd frequency,最后判断这个数是不是小于等于1。

class Solution {
public:
    bool canPermutePalindrome(string s) {
        int odd = 0;
        int mp[256] = {0};
        for(char c : s) odd += ((++mp[c] % 2) == 1) ? 1 : -1;
        return odd<=1;
    }
};
发布了109 篇原创文章 · 获赞 0 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章