To find the length of the longest palindrome that can be built from a given string, we count
the frequency of each character. A palindrome can have at most one character with an
odd frequency (the
middle character),
while all other characters must have
even frequencies. We
calculate the total
number of
pairs of
characters and
check if
there is at least one character with an odd frequency. If so, we
add 1 to the total length
to account for the middle character.
class Solution { public int longestPalindrome(String s) { int[] sHash = new int[130]; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); sHash[ch]++; } boolean hasOdd = false; int pairs=0; for(int i=0;i<130;i++){ if(sHash[i]%2==1) hasOdd = true; pairs += sHash[i]/2; } if(hasOdd) return 2*pairs+1; else return 2*pairs; } }
The algorithm iterates through the string once to count character frequencies and then iterates through the frequency array, making it linear in time complexity.
The algorithm uses a fixed-size frequency array, ensuring constant space usage.