Skip to content

Latest commit

 

History

History
126 lines (99 loc) · 2.31 KB

File metadata and controls

126 lines (99 loc) · 2.31 KB

中文文档

Description

Given a string s, return true if a permutation of the string could form a palindrome and false otherwise.

 

Example 1:

Input: s = "code"
Output: false

Example 2:

Input: s = "aab"
Output: true

Example 3:

Input: s = "carerac"
Output: true

 

Constraints:

  • 1 <= s.length <= 5000
  • s consists of only lowercase English letters.

Solutions

Python3

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

Java

class Solution {
    public boolean canPermutePalindrome(String s) {
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) {
            ++cnt[c - 'a'];
        }
        int n = 0;
        for (int v : cnt) {
            n += v % 2;
        }
        return n < 2;
    }
}

C++

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

Go

func canPermutePalindrome(s string) bool {
	cnt := make([]int, 26)
	for _, c := range s {
		cnt[c-'a']++
	}
	n := 0
	for _, v := range cnt {
		n += v & 1
	}
	return n < 2
}

JavaScript

/**
 * @param {string} s
 * @return {boolean}
 */
var canPermutePalindrome = function (s) {
    let ss = new Set();
    for (let c of s) {
        if (ss.has(c)) {
            ss.delete(c);
        } else {
            ss.add(c);
        }
    }
    return ss.size < 2;
};

...