Advertisement
gelita

anagram palindrome

Feb 8th, 2020
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.90 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. class MyCode {
  6.  
  7.   /**
  8.      * 10 Anagram Palindrome
  9.      *
  10.      *  Given a string, determine if the string can be rearranged to form a palindrome.
  11.      *
  12.      *  A palindrome is a word that is the same as its reversed. For example: "racecar"
  13.      *  and "noon" are palindromes because they match their reversed version
  14.      *  respectively. On the other hand, "cat" is not a palindrome because "cat"
  15.      *  does not equal "tac".
  16.      *
  17.      *  Parameters
  18.      *  Input: str {String}
  19.      *  Output: {Boolean}
  20.      *
  21.      *  Constraints
  22.      *
  23.      *  Assume the string only contains lowercase letters and no spaces.
  24.      *
  25.      *  Time: O(N)
  26.      *  Space: O(1)
  27.      *
  28.      *  Examples
  29.      *  `"carrace" --> true ("carrace" can be rearranged to "racecar")`
  30.      *  `"cat" --> false`
  31.      */
  32.   public static void main (String[] args) {
  33.         String str = "carrace";
  34.     //String str = "cccj";
  35.     Boolean results;
  36.     results = anagramPalindrome(str);
  37.     System.out.println(results);
  38.     }
  39.  
  40.   public static Boolean anagramPalindrome(String str) {
  41.     //only lowercase letters --> 128 is possible char count
  42.     int CHAR_COUNT = 128;
  43.     int[] countArr = new int[CHAR_COUNT];
  44.     //fill array w/all chars found in input string and set count of each to 0
  45.     Arrays.fill(countArr,0);
  46.     for(int i = 0; i < str.length(); i++){
  47.       //increment the count for each car found in string
  48.       countArr[(int)str.charAt(i)]++;
  49.     }
  50.     //for a palindrome there can only be 0 or 1 chars w/odd counts
  51.     int numOdds = 0;
  52.     for(int index = 0; index < CHAR_COUNT; index++){
  53.       //is the count for this char odd?
  54.       if((countArr[index] & 1) == 1  ){
  55.         numOdds++;
  56.       }
  57.       if(numOdds > 1){
  58.         //if there is more than one single char than not a palindrome
  59.         return false;          
  60.       }
  61.     }
  62.     return true;
  63.   }      
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement