Leetcode 409. Longest Palindrome
Given a string s
which consists of lowercase or uppercase letters, you need to find the length of the longest palindrome that can be built with those letters.
Input: s = "abccccdd"
Output: 7
Explanation: One of the longest palindromes that can be built is “dccaccd”, whose length is 7
.
s
is non-empty.To determine the length of the longest palindrome that can be built, follow these steps:
This approach ensures that we maximize the length of the palindrome.
Here’s a Java solution implementing the above strategy:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int longestPalindrome(String s) {
// Step 1: Count the frequency of each character
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
// Step 2: Calculate the length of the longest palindrome
int length = 0;
boolean oddFrequencyFound = false;
for (int count : frequencyMap.values()) {
if (count % 2 == 0) {
length += count;
} else {
length += count - 1; // Add the even part of the count
oddFrequencyFound = true;
}
}
// Step 3: If any odd frequency was found, add 1 to the length
if (oddFrequencyFound) {
length += 1;
}
return length;
}
public static void main(String[] args) {
Solution sol = new Solution();
String input = "abccccdd";
int result = sol.longestPalindrome(input);
System.out.println("The length of the longest palindrome that can be built is: " + result);
}
}
s
. This is because we iterate over the string once to build the frequency map and then iterate over the frequency map keys to calculate the length.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?