[LeetCode266]Palindrome Permutation

来源:互联网 发布:bu大都会学院知乎 编辑:程序博客网 时间:2024/05/23 00:02
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 UberHide Tags Hash TableHide 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;    }};
0 0
原创粉丝点击