
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Even Length Substring That Is Permutation of a Palindrome in C++
Problem statement
Given a string the task is to find the maximum length of the sub-string of that can be arranged into a Palindrome.
Example
If input string = “5432112356” then answer is 6 as maximum palindrome substring is “321123” and its length is 6
Algorithm
- If the length of the sub-string is odd, then it cannot be considered in the final solutions.
- If the length of the sub-string is even, then it can be a possible solution only if each character in that sub-string occurs even number of times which can be done using the dictionary count. We check if each character occurs even number of times or not. If yes, then we include it as one of the possible solutions. Then we form the next sub-string by including the next character in the string which can be done by simply incrementing end and check recursively if a sub-string with greater length can be formed which satisfies the given conditions and return the maximum of all possible solutions
Example
#include <bits/stdc++.h> using namespace std; unordered_map<int, int> countt; bool isPalindromePossible(unordered_map<int, int> &countt) { for (auto key : countt) { if (key.second & 1) { return false; } return true; } int getMaxPalindrome(string str, unordered_map<int, int> &countt, int start, int end) { if (end == str.length()) { if ((end - start) % 2 == 0) if (isPalindromePossible(countt)) return end - start; return 0; } else { if ((end - start) % 2 == 0) { if (isPalindromePossible(countt)) { countt[str[end]]++; return max(end - start, getMaxPalindrome(str, countt, start, end + 1)); } else { countt[str[end]]++; return getMaxPalindrome(str, countt, start, end + 1); } } else { countt[str[end]]++; unordered_map<int, int> c(countt.begin(), countt.end()); int length = getMaxPalindrome(str, c, start, end + 1); countt[str[end]]--; countt[str[start]]--; return max(length, getMaxPalindrome(str, countt, start + 1, end)); } } } int main(int argc, char const *argv[]) { string str = "5432112356"; int start = 0, end = 0; cout << "Maximum palindrome length = " << getMaxPalindrome(str, countt, start, end) << endl; return 0; }
Output
When you compile and execute above program. It generates following output −
Maximum palindrome length = 6
Advertisements