Java Solution; O(n) running time, O(1) memory, 11ms.


  • 0
    S
    public int longestPalindrome(String s) {
      if (s == null || s.isEmpty()) return 0;
    
      final int l = s.length();
      if (l == 1) return 1;
    
      final int[] counter = new int[52]; // [a-zA-Z]
      for (int i = 0; i < l; i++) {
        final char ch = s.charAt(i);
        if (Character.isUpperCase(ch)) {
          counter[26 + (ch - 'A')]++;
        } else {
          counter[ch - 'a']++;
        }
      }
    
      int even = 0;
      boolean hasOdd = false;
    
      for (int i: counter) {
        even += (i & ~1);
        hasOdd = hasOdd || ((i & 1) == 1);
      }
    
      return even + (hasOdd ? 1 : 0);
    }
    

Log in to reply
 

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