8ms Java implementation with O(n) time, 1 space complexity,


  • 0
    U
    ```public int longestPalindrome(String s) {
        int length = 0; 
        int spares = 0; 
        char[] charArray = s.toCharArray(); 
        int[] counter = new int['z'-'A'+1]; // a little more than 52. 
    
        int i; 
        for (char c : charArray ) {
            i = c-'A';
            if (counter[i] == 0) {
                counter[i]++;
                spares++;
            }
            else { //it's one. 
                counter[i]--;
                spares--; 
                length += 2; 
            }
        }
    
        if (spares > 0) length++;
        return length; 
    }```

Log in to reply
 

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