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
Minimum number of Appends needed to make a string palindrome in C++
Problem statement
Given a string, find minimum characters to be appended to make a string palindrome.
Example
If string is abcac then we can make string palindrome by appending 2 highlighed characters i.e. abcacba
Algorithm
- Check if string is already palindrome, if yes then no need to append any characters.
- One by one remove a character from string and check whether remaining string is palindrome or not
- Repeat above process until string becomes palidrome
- Return the number of characters removed so far as a final answer
Example
#include <iostream>
#include <cstring>
using namespace std;
bool isPalindrome(char *str) {
int n = strlen(str);
if (n == 1) {
return true;
}
int start = 0, end = n - 1;
while (start < end) {
if (str[start] != str[end]) {
return false;
}
++start;
--end;
}
return true;
}
int requiredAppends(char *str) {
if (isPalindrome(str)) {
return 0;
}
return 1 + requiredAppends(str + 1);
}
int main() {
char *str = "abcac";
cout << "Characters to be appended = " << requiredAppends(str) << endl;
return 0;
}
Output
When you compile and execute above program. It generates following output −
Characters to be appended = 2
Advertisements