Minimum number of deletions to make a string palindrome in C++.



Problem statement

Given a string of size β€˜n’. The task is to delete a minimum number of characters to make string palindrome.

If the given string is β€œabcda” then we can delete any 2 characters except first and last to make it a palindrome.

  • If we delete character β€˜b’ and β€˜c’ then β€œada” string is a palindrome

  • If we delete character β€˜c’ and β€˜d’ then β€œaba” string is a palindrome

  • If we delete character β€˜b’ and β€˜d’ then β€œaca” string is a palindrome

Algorithm

1. Find longest palindromic subsequence of given string. Let’s call it as β€œlpsSize”.
2. Minimum characters to be deleted = (length of string – lpsSize) Code.

Example

#include <iostream>
#include <algorithm>
using namespace std;
int lps(string s, int i, int j){
   if (i == j) {
      return 1;
   }
   if (s[i] == s[j] && i + 1 == j) {
      return 2;
   }
   if (s[i] == s[j]) {
      return lps(s, i + 1, j - 1) + 2;
   }
   return max(lps(s, i, j - 1), lps(s, i + 1, j));
}
int minDeletion(string s){
   int n = s.size();
   int lpsSize = lps(s, 0, n);
   return (n - lpsSize);
}
int main(){
   cout << "Minimum characters to be deleted = " <<
   minDeletion("abcda") << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output βˆ’

Minimum characters to be deleted = 2
Updated on: 2019-10-31T06:40:01+05:30

990 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements