Java, simple logic with explain O(n)


  • 0
    M

    Simple logic, count how many number of character in string is even, if the number is smaller than the length of s, then there is palindrome permutation with an extra unique character from s, otherwise, how many number of characters with even occurrence can be doubled to form a palindrome.

    class Solution {
        public int longestPalindrome(String s) {
            Map<Character, Integer>map = new HashMap<>();
            int count = 0;
            for(char c : s.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
                
                if(map.get(c)%2 == 0) count++;
            }
            
            if(count*2 == s.length()) return count*2;
            if(count*2 < s.length()) return count*2 + 1;
            
            return count;
        }
    }
    

Log in to reply
 

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