We have given an anagram string and we have to check whether it can be made palindrome o not in C++.
Examples:
Input : geeksforgeeks Output : No There is no palindrome anagram of given string Input : geeksgeeks Output : Yes There are palindrome anagrams of given string. For example kgeesseegk
This problem is basically the same as Check if characters of a given string can be rearranged to form a palindrome. We can do it in O(n) time using a count array. Following are detailed steps.
1) Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0.
2) Traverse the given string and increment count of every character.
3) Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true.
#include using namespace std; #define NO_OF_CHARS 256 /* function to check whether characters of a string can form a palindrome */ bool canFormPalindrome(string str) { // Create a count array and initialize all // values as 0 int count[NO_OF_CHARS] = { 0 }; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; str[i]; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if (count[i] & 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } /* Driver program to test to print printDups*/ int main() { canFormPalindrome("geeksforgeeks") ? cout << "Yes\n" : cout << "No\n"; canFormPalindrome("geeksogeeks") ? cout << "Yes\n" : cout << "No\n"; return 0; }
Output:
No Yes
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.