In: Computer Science
C#
Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
Input: Tact Coa
Output: True (permutations: "taco cat", "atco cta", etc.)
Comment your code to explain it.
// if you have any problem let em know i will try to help you. Thank you.
using System;
class MainClass {
public static bool isPallindromePermutation(string str)
{
str=str.ToLower(); // convert the string to lowercase
int[] arr;
arr=new int[26]; // an array to store the count of each character
int odd=0; // count number of odd numbers times any character occurs
for(int i=0;i<26;i++){
arr[i]=0;
}
for(int i=0;i<str.Length;i++)
{
if(str[i]!=' '){ // it is not space
int k=(str[i]-'a');
arr[k]=arr[k]+1;
}
}
foreach(int a in arr)
{
if(a%2!=0)
odd++;
}
if(odd<=1) // if there is only one character or no character with odd number of times occur then it is possible
return true;
else
return false;
}
public static void Main (string[] args) {
Console.WriteLine("Enter a string: ");
string str=Console.ReadLine();
Console.WriteLine (isPallindromePermutation(str));
}
}
// Sample output:-