Palindrome Permutation Check
Problem
Print true if the letters of the word can be rearranged to make a palindrome, otherwise false.
Constraints
- 1 <= length <= 10^5
- lowercase letters
Examples
Input
carrace
Output
true
Input
abc
Output
false
Solutions
In a palindrome every letter comes in pairs, except maybe one in the middle. So at most one letter may have an odd count.
/*
* Problem : Palindrome from letters?
* Input : One word.
* Output : true or false.
* Approach: Count odd letters.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static boolean solve(String s) {
// Step 1: A palindrome has at most one letter with an odd count (the middle one).
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
counts[s.charAt(i) - 'a']++;
}
// Step 2: Count the letters whose count is odd.
int odd = 0;
for (int count : counts) {
if (count % 2 == 1) {
odd++;
}
}
return odd <= 1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- How many letters can be in the middle?