sweet1cris

Untitled

Feb 9th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1.  
  2. // version 1
  3. public class Solution {
  4.     /**
  5.      * @param s a string which consists of lowercase or uppercase letters
  6.      * @return the length of the longest palindromes that can be built
  7.      */
  8.     public int longestPalindrome(String s) {
  9.         // Write your code here
  10.         Set<Character> set = new HashSet<>();
  11.         for (char c : s.toCharArray()) {
  12.             if (set.contains(c)) set.remove(c);
  13.             else set.add(c);
  14.         }
  15.  
  16.         int remove = set.size();
  17.         if (remove > 0)
  18.             remove -= 1;
  19.         return s.length() - remove;
  20.     }
  21. }
  22.  
  23. // version 2
  24. public class Solution {
  25.     public int longestPalindrome(String s) {
  26.         int[] charStatArray = new int[52];
  27.         int oneTimeOddCount = 0;
  28.         int evenCount = 0;
  29.    
  30.         // zero clearing of the array
  31.         //memset(charStatArray, 0, sizeof(charStatArray));
  32.    
  33.         // keep the times of appearance of each character in the array
  34.         for (char ch: s.toCharArray()) {
  35.             if (ch >= 97) {
  36.                 charStatArray[26 + ch - 'a']++;
  37.             }
  38.             else {
  39.                 charStatArray[ch - 'A']++;
  40.             }
  41.         }
  42.    
  43.         // the answer is the count of characters that has even number of appereances.
  44.         // for characters that has odd number of appereances,
  45.         // their appereances minus 1 will make their apperances even.
  46.         // And finally we can put an unused character in the middle of the palindrome
  47.         // (if there is any).
  48.         for (int cnt: charStatArray) {
  49.             if (cnt != 0) {
  50.                 if (cnt % 2 == 0) {
  51.                     evenCount += cnt;
  52.                 } else {
  53.                     if (cnt == 1) {
  54.                         oneTimeOddCount++;
  55.                     }
  56.                     else {
  57.                         evenCount += cnt - 1;
  58.                         oneTimeOddCount++;
  59.                     }
  60.                 }
  61.             }
  62.         }
  63.    
  64.         return oneTimeOddCount > 0 ? 1 + evenCount : evenCount;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment