Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class MyCode {
- /**
- * 10 Anagram Palindrome
- *
- * Given a string, determine if the string can be rearranged to form a palindrome.
- *
- * A palindrome is a word that is the same as its reversed. For example: "racecar"
- * and "noon" are palindromes because they match their reversed version
- * respectively. On the other hand, "cat" is not a palindrome because "cat"
- * does not equal "tac".
- *
- * Parameters
- * Input: str {String}
- * Output: {Boolean}
- *
- * Constraints
- *
- * Assume the string only contains lowercase letters and no spaces.
- *
- * Time: O(N)
- * Space: O(1)
- *
- * Examples
- * `"carrace" --> true ("carrace" can be rearranged to "racecar")`
- * `"cat" --> false`
- */
- public static void main (String[] args) {
- String str = "carrace";
- //String str = "cccj";
- Boolean results;
- results = anagramPalindrome(str);
- System.out.println(results);
- }
- public static Boolean anagramPalindrome(String str) {
- //only lowercase letters --> 128 is possible char count
- int CHAR_COUNT = 128;
- int[] countArr = new int[CHAR_COUNT];
- //fill array w/all chars found in input string and set count of each to 0
- Arrays.fill(countArr,0);
- for(int i = 0; i < str.length(); i++){
- //increment the count for each car found in string
- countArr[(int)str.charAt(i)]++;
- }
- //for a palindrome there can only be 0 or 1 chars w/odd counts
- int numOdds = 0;
- for(int index = 0; index < CHAR_COUNT; index++){
- //is the count for this char odd?
- if((countArr[index] & 1) == 1 ){
- numOdds++;
- }
- if(numOdds > 1){
- //if there is more than one single char than not a palindrome
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement