Created
September 13, 2017 21:23
-
-
Save cixuuz/dde3a93502691ecbed719ea4d3b38f58 to your computer and use it in GitHub Desktop.
[409. Longest Palindrome] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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