[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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章