Java Solution using HashSet and O(n) time complexity


  • 0
    T
    public class Solution {
        public int longestPalindrome(String s) {
            Set<Character> set = new HashSet<Character>();
            
            for(char c : s.toCharArray()){
                if(set.contains(c)){
                    set.remove(c);
                }else{
                    set.add(c);
                }
            }
            
            int odd = set.size();
            return s.length() -(odd == 0 ? 0: odd-1);
        }
    }
    
    

Log in to reply
 

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