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

CoderIndeed
0
0409. Longest Palindrome

Description

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome.

 

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

 

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase English letters only.

Solutions

Solution 1: Counting

A valid palindrome string can have at most one character that appears an odd number of times, and the rest of the characters appear an even number of times.

Therefore, we can first traverse the string s, count the number of occurrences of each character, and record it in an array or hash table cnt.

Then, we traverse cnt, for each count v, we divide v by 2, take the integer part, multiply by 2, and add it to the answer ans.

Finally, if the answer is less than the length of the string s, we increment the answer by one and return ans.

The time complexity is O(n + |Σ|), and the space complexity is O(|Σ|). Where n is the length of the string s, and |Σ| is the size of the character set. In this problem, |Σ| = 128.

PythonJavaC++GoTypeScriptRust
class Solution: def longestPalindrome(self, s: str) -> int: cnt = Counter(s) ans = sum(v // 2 * 2 for v in cnt.values()) ans += int(ans < len(s)) return ans(code-box)

Solution 2: Bit Manipulation + Counting

We can use an array or hash table odd to record whether each character in string s appears an odd number of times, and an integer variable cnt to record the number of characters that appear an odd number of times.

We iterate through the string s. For each character c, we flip odd[c], i.e., 0 \rightarrow 1, 1 \rightarrow 0. If odd[c] changes from 0 to 1, then we increment cnt by one; if odd[c] changes from 1 to 0, then we decrement cnt by one.

Finally, if cnt is greater than 0, the answer is n - cnt + 1, otherwise, the answer is n.

The time complexity is O(n), and the space complexity is O(|Σ|). Where n is the length of the string s, and |Σ| is the size of the character set. In this problem, |Σ| = 128.

PythonJavaC++GoTypeScript
class Solution: def longestPalindrome(self, s: str) -> int: odd = defaultdict(int) cnt = 0 for c in s: odd[c] ^= 1 cnt += 1 if odd[c] else -1 return len(s) - cnt + 1 if cnt else len(s)(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 !