Java solution with detailed explanation !

  • 0

    Basic idea is to count the odd occurrence of character in the string, we iterate the char array and using set to store all the odd number of chars, at the end there are two cases:

    1. set has zero elements or set has only one elements, in these two cases we could simply return the string size as the result (ex : "aabbcc----> abccba" or "aabbccd"----> abcdcba)
    2. set has more than two elements, which means we still can take one of them and put in our final result since palindrome could allow one single element in the very middle. (ex "aabbcd ---> abcba" or "aabbbc ---> abcba"

    Hope my explanation is clear.

    public class Solution {
        public int longestPalindrome(String s) {
            Set<Character> set = new HashSet<>();
            char[] arr = s.toCharArray();
            for(char c : arr){
            int singleNumber = set.size() >= 2 ? set.size() - 1 : 0;
            return s.length() - singleNumber;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.