This is the Java Program to Check if Any Anagram of the String is a Palindrome
Given a string, check whether any of its anagrams is palindrome or not. An anagram is just a new word formed by permuting the letters of the string.
Example:
String x = “ACBDABD”
Output = Yes
Count the frequency of each character in the string. If there is only one character, whose frequency is odd, and rest of the frequencies are even, then print Yes, otherwise print No.
Here is the source code of the Java Program to Check if Any Anagram of the String is a Palindrome. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Check if Any Anagram of the String is a Palindrome
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PalindromeAnagram {
// Function check if any palindrome anagram exists
static boolean anagram(String str){
int[] arr = new int[256];
int i;
for(i=0; i<str.length(); i++){
arr[str.charAt(i)]++;
}
int odd,even;
odd = even =0;
for(i=0; i<256; i++){
if(arr[i] % 2 == 0)
even++;
else
odd++;
}
boolean result;
if(odd > 1)
return false;
return true;
}
// Function to read input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
} catch (IOException e) {
System.out.println("An I/O error occurred");
return;
}
boolean result = anagram(str);
if(result)
System.out.println("Palindrome anagrams exist");
else
System.out.println("No palindrome anagrams exists");
}
}
1. In function anagram(), an array is created to length 256 to count the frequency of various characters as per ASCII code.
2. The loop for(i=0; i<str.length(); i++) traverses through the whole string and counts the frequency of each character.
3. The loop for(i=0; i<256; i++) traverses through the array and count the number of characters having even frequencies and odd frequencies.
4. The condition if(odd > 1) checks if the number of characters having odd frequency is more than 1, false is returned, otherwise true is returned.
Time Complexity: O(n) where n is the length of the string.
Case 1 (Positive Test Case): Enter the string ACBDABD Palindrome anagrams exist Case 2 (Negative Test Case): Enter the string bcddacbaaf No palindrome anagrams exists
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Programming Books
- Check Java Books
- Practice BCA MCQs
- Apply for Computer Science Internship
- Practice Information Technology MCQs