“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
[B] [C] [D]
Given a string containing both uppercase and lowercase letters, find the longest palindrome string constructed from these letters.
Pay attention to case sensitivity during construction. For example, “Aa” cannot be treated as a palindrome string.
Note: The string is assumed to be no longer than 1010.
Example 1:
Input: "abccCCdd" Output: 7 Explanation: The longest palindrome string we can construct is "dCCaccd ", which is 7 in length.Copy the code
First, let’s look at the properties of palindromes, using the palindromes in Example 1
dccaccd
A palindrome string traverses the string from left to right, giving the same result as traversing the string from right to left
That is, the left and right parts of the palindrome string are the same
If the length of the palindrome string is odd, the middle part is one character, and the middle part is two identical characters
Regardless of the middle position, the character composition of the left and right parts is consistent, which means that the number of occurrences of each character is even
So we can iterate over the input string and map each character and how many times it occurs
Record the length of the longest palindrome string that can be formed using the variable total, which is initialized to 0
Next, the map is iterated, and if the number of occurrences of the current character is unusual, total accumulates the number of occurrences of the current character minus 1 (because no middle character is currently guaranteed to occur even times in the resulting string).
If the number of current character occurrences is even, total sums the number of current character occurrences
Finally, if total is equal to the length of the input string, it indicates that each character in the input string appears an even number of times. Return total
Otherwise, it means that at least one of the characters in the input string occurs an odd number of times, because we want to find the longest palindrome string length, and because we currently place any more characters in the middle of the resulting string without violating palindrome properties, we return total+1
At this point, the problem is solved. The code is as follows:
var longestPalindrome = function(s) { const len = s.length, map = new Map(); For (let I = 0; i<len; I ++){const cur = s[I] if(map.has(cur)){map.set(cur,map.get(cur)+1)}else{map.set(cur,1)} total = 0; For (let item of map){if(item[1]%2) total += item[1]-1 else Total += item[1]} // If the sum is smaller than the input string length // If (total<len) return total+1 // If total===len each type of character in the input string has an even number of occurrences return total; };Copy the code
At this point we have completed leetcode-409- the longest palindrome string
If you have any questions or suggestions, please leave a comment!