Java Solution using HashMap


  • 0
    A
    public class Solution {
        public int longestPalindrome(String s) {
            if(s.length()==0) return 0;
            int count=0;
            boolean oddNumber=false;
            HashMap<Character,Integer> h = new HashMap<Character,Integer>();
            for(int i=0;i<s.length();i++){
                if(!h.containsKey(s.charAt(i))) h.put(s.charAt(i),1);
                else h.put(s.charAt(i),h.get(s.charAt(i))+1);
            }
            for(Map.Entry<Character,Integer> m:h.entrySet()){
                if(m.getValue()%2==0) count+=m.getValue();
                else{
                    count+=m.getValue()-1;
                    oddNumber=true;
                }
            }
            if(oddNumber==false) return count;
            return count+1;
        }
    }
    

Log in to reply
 

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