Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created September 13, 2017 21:23
Show Gist options
  • Select an option

  • Save cixuuz/dde3a93502691ecbed719ea4d3b38f58 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/dde3a93502691ecbed719ea4d3b38f58 to your computer and use it in GitHub Desktop.
[409. Longest Palindrome] #leetcode
class Solution {
// O(n) O(1)
public int longestPalindrome(String s) {
if (s.length() == 0 || s == null) return 0;
int[] counts = new int[52];
for (Character c : s.toCharArray()) {
int idx = 0;
if (c.compareTo('a') < 0) {
idx = (int) c - 'A';
} else {
idx = (int) c - 'a';
idx += 26;
}
counts[idx]++;
}
boolean flag = false;
int res = 0;
for (int count : counts) {
if (count % 2 == 0) {
res += count;
} else {
res += count - 1;
flag = true;
}
}
return flag? res + 1 : res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment