Dare2Solve
The problem asks for the length of the longest palindrome that can be built using characters from the input string s
. A palindrome is a string that reads the same backward as forward. We are allowed to rearrange the characters of s
to form the longest possible palindrome. The task is to return the length of that palindrome.
To form a palindrome, characters need to appear an even number of times to ensure symmetry. For instance, the character "a" can appear twice and still be placed in both the left and right halves of the palindrome. If a character appears an odd number of times, one instance can still be placed in the center of the palindrome. Therefore, the idea is to count how many characters can form pairs and if any odd-frequency character can be placed in the middle.
O(n), where n
is the length of the string s
. We traverse the string once to build the frequency map and then iterate through the map to compute the length of the palindrome.
O(1) or O(c), where c
is the number of unique characters. Since the character set is limited (e.g., 26 for lowercase English letters), the space complexity is considered constant.
class Solution {
public:
int longestPalindrome(string s) {
if (s.length() < 2)
return s.length();
unordered_map<char, int> map;
int longest = 0;
for (char c : s) {
map[c]++;
if (map[c] % 2 == 0)
longest += 2;
}
if (s.length() > longest)
longest += 1;
return longest;
}
};
class Solution:
def longestPalindrome(self, s: str) -> int:
if len(s) < 2:
return len(s)
char_count = {}
longest = 0
for char in s:
char_count[char] = char_count.get(char, 0) + 1
if char_count[char] % 2 == 0:
longest += 2
if len(s) > longest:
longest += 1
return longest
class Solution {
public int longestPalindrome(String s) {
if (s.length() < 2) return s.length();
HashMap<Character, Integer> map = new HashMap<>();
int longest = 0;
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
if (map.get(c) % 2 == 0) longest += 2;
}
if (s.length() > longest) longest += 1;
return longest;
}
}
/**
* @param {string} s
* @return {number}
*/
var longestPalindrome = function (s) {
if (s.length < 2) return s.length;
const map = {};
let longest = 0;
for (let i = 0; i < s.length; i++) {
map[s[i]] = (map[s[i]] || 0) + 1;
if (map[s[i]] % 2 === 0) longest += 2;
}
if (s.length > longest) longest += 1;
return longest;
};