Skip to content

Latest commit

 

History

History
102 lines (74 loc) · 2.08 KB

File metadata and controls

102 lines (74 loc) · 2.08 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) {
        int[] counter = new int[26];
        for (char c : s.toCharArray()) {
            ++counter[c - 'a'];
        }
        int oddCnt = 0;
        for (int cnt : counter) {
            oddCnt += cnt % 2;
        }
        return oddCnt < 2;
    }
}

C++

class Solution {
public:
    bool canPermutePalindrome(string s) {
        vector<int> counter(26);
        for (auto& c : s) ++counter[c - 'a'];
        int oddCnt = 0;
        for (int& cnt : counter) oddCnt += cnt % 2;
        return oddCnt < 2;
    }
};

Go

func canPermutePalindrome(s string) bool {
	counter := make([]int, 26)
	for i := range s {
		counter[s[i]-'a']++
	}
	oddCnt := 0
	for _, cnt := range counter {
		oddCnt += cnt % 2
	}
	return oddCnt < 2
}

...