10 ms Java solution


  • 3
    H
    public class Solution {
        public int longestPalindrome(String s) {
            if(s==null|| s.length()==0)
            return 0;
            if(s.length()==1)
            return 1;
            
            int[] alpha=new int[128];
            int max_length=0;
            for(char c:s.toCharArray()){
                alpha[c]++;
                if(alpha[c]==2)
                {
                    max_length+=2;
                    alpha[c]=0;
                }
            }
            if(s.length()>max_length)
             return max_length+1;
            else
             return max_length;
            
        }
    }
    

    Just check for pairs in the String and increment max_length. At the end compare the String length and max_length to determine whether the whole string is a palindrome or not.

    O(n) solution.


Log in to reply
 

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