LeetCode 0266. Palindrome Permutation Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0266. Palindrome Permutation

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

Solution 1: Counting

If a string is a palindrome, at most one character can appear an odd number of times, while all other characters must appear an even number of times. Therefore, we only need to count the occurrences of each character and then check if this condition is satisfied.

Time complexity is O(n), and space complexity is O(|Σ|). Here, n is the length of the string, and |Σ| is the size of the character set. In this problem, the character set consists of lowercase letters, so |Σ|=26.

PythonJavaC++GoTypeScriptJavaScript
class Solution: def canPermutePalindrome(self, s: str) -> bool: return sum(v & 1 for v in Counter(s).values()) < 2(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !