zoukankan      html  css  js  c++  java
  • [LeetCode] Palindrome Permutation

    Problem Description:

    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?

    Just check there are no more than 2 characters that appear an odd number of times in the string.

    My C++ code using an array as a hash map is as follows.

    1 class Solution {
    2 public:
    3     bool canPermutePalindrome(string s) {
    4         int odd = 0, counts[256] = {0};
    5         for (char c : s)
    6             odd += ++counts[c] & 1 ? 1 : -1;
    7         return odd <= 1;
    8     }
    9 };

    BTW, Stefan has posted many nice solutions here, including the following one that uses bitset.

    1 class Solution {
    2 public:
    3     bool canPermutePalindrome(string s) {
    4         bitset<256> b;
    5         for (char c : s) b.flip(c);
    6         return b.count() < 2;
    7     }
    8 };
  • 相关阅读:
    数据结构实验之栈四:括号匹配
    数据结构实验之栈三:后缀式求值
    8月7日学习
    8月6日学习
    8月5日学习
    8月4日学习
    周总结
    8月3日学习
    8月2日学习
    8月1日学习
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4748554.html
Copyright © 2011-2022 走看看