Java Array solution beats 85%


  • 0
    Z

    'z' - 'A' + 1 = 58;
    so u can count the characters and save them into a int[58] instead of int[52] which will reduce the time of checking the lower/upper case of characters.

    class Solution {
        public int longestPalindrome(String s) {
            int[] count = new int[58];
            int ret = 0; boolean odd = false;
            for(int i = 0; i < s.length(); i ++){
                count[s.charAt(i)-'A']++;
            }
            
            for(int i = 0; i < 58; i++){ 
                ret += count[i];
                if(count[i]%2 != 0) {
                    ret --;
                    odd = true;
                }
            }
            
            return odd ? ret + 1 : ret;
        }
    }
    

Log in to reply
 

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