Skip to content

Latest commit

 

History

History
102 lines (74 loc) · 2.17 KB

File metadata and controls

102 lines (74 loc) · 2.17 KB

English Version

题目描述

给定一个字符串,判断该字符串中是否可以通过重新排列组合,形成一个回文字符串。

示例 1:

输入: "code"
输出: false

示例 2:

输入: "aab"
输出: true

示例 3:

输入: "carerac"
输出: true

解法

利用 HashMap(字典表)统计每个字符出现的频率,至多有一个字符出现奇数次数即可。

Python3

class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        counter = Counter(s)
        return sum(e % 2 for e in counter.values()) < 2

Java

class Solution {
    public boolean canPermutePalindrome(String s) {
        Map<Character, Integer> counter = new HashMap<>();
        for (char c : s.toCharArray()) {
            counter.put(c, counter.getOrDefault(c, 0) + 1);
        }
        int oddCnt = 0;
        for (int e : counter.values()) {
            oddCnt += e % 2;
        }
        return oddCnt < 2;
    }
}

C++

class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map<char, int> counter;
        for (char c : s) ++counter[c];
        int oddCnt = 0;
        for (auto& it : counter) oddCnt += it.second % 2;
        return oddCnt < 2;
    }
};

Go

func canPermutePalindrome(s string) bool {
    counter := make(map[rune]int)
    for _, c := range s {
        counter[c]++
    }
    oddCnt := 0
    for _, e := range counter {
        oddCnt += e % 2
    }
    return oddCnt < 2
}

...