|
| 1 | +/** |
| 2 | + * Given a string which consists of lowercase or uppercase letters, find the |
| 3 | + * length of the longest palindromes that can be built with those letters. |
| 4 | + * |
| 5 | + * This is case sensitive, for example "Aa" is not considered a palindrome here. |
| 6 | + * |
| 7 | + * Note: |
| 8 | + * Assume the length of given string will not exceed 1,010. |
| 9 | + * |
| 10 | + * Example: |
| 11 | + * Input: |
| 12 | + * "abccccdd" |
| 13 | + * Output: |
| 14 | + * 7 |
| 15 | + * |
| 16 | + * Explanation: |
| 17 | + * One longest palindrome that can be built is "dccaccd", whose length is 7. |
| 18 | + */ |
| 19 | + |
| 20 | +public class LongestPalindrome409 { |
| 21 | + public int longestPalindrome(String s) { |
| 22 | + Map<Character, Integer> map = new HashMap<>(); |
| 23 | + for (char ch: s.toCharArray()) { |
| 24 | + map.put(ch, map.getOrDefault(ch, 0) + 1); |
| 25 | + } |
| 26 | + |
| 27 | + int res = 0; |
| 28 | + boolean hasOdd = false; |
| 29 | + for (int i: map.values()) { |
| 30 | + if (i % 2 == 0) { |
| 31 | + res += i; |
| 32 | + } else { |
| 33 | + res += i - 1; |
| 34 | + hasOdd = true; |
| 35 | + } |
| 36 | + } |
| 37 | + return res + (hasOdd ? 1 : 0); |
| 38 | + } |
| 39 | + |
| 40 | + |
| 41 | + /** |
| 42 | + * https://leetcode.com/problems/longest-palindrome/discuss/89604/Simple-HashSet-solution-Java |
| 43 | + */ |
| 44 | + public int longestPalindrome2(String s) { |
| 45 | + if(s==null || s.length()==0) return 0; |
| 46 | + HashSet<Character> hs = new HashSet<Character>(); |
| 47 | + int count = 0; |
| 48 | + for(int i=0; i<s.length(); i++){ |
| 49 | + if(hs.contains(s.charAt(i))){ |
| 50 | + hs.remove(s.charAt(i)); |
| 51 | + count++; |
| 52 | + }else{ |
| 53 | + hs.add(s.charAt(i)); |
| 54 | + } |
| 55 | + } |
| 56 | + if(!hs.isEmpty()) return count*2+1; |
| 57 | + return count*2; |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + /** |
| 62 | + * https://leetcode.com/problems/longest-palindrome/discuss/89610/Simple-Java-Solution-in-One-Pass |
| 63 | + */ |
| 64 | + public int longestPalindrome3(String s) { |
| 65 | + boolean[] map = new boolean[128]; |
| 66 | + int len = 0; |
| 67 | + for (char c : s.toCharArray()) { |
| 68 | + map[c] = !map[c]; // flip on each occurrence, false when seen n*2 times |
| 69 | + if (!map[c]) len+=2; |
| 70 | + } |
| 71 | + if (len < s.length()) len++; // if more than len, atleast one single is present |
| 72 | + return len; |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments