

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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
- Related Questions & Answers
- Minimum number of Appends needed to make a string palindrome in C++
- Program to find minimum deletions to make string balanced in Python
- Minimum Insertion Steps to Make a String Palindrome in C++
- Program to check minimum number of characters needed to make string palindrome in Python
- Finding minimum deletions in string in JavaScript
- Program to find minimum deletions to make strings strings in Python
- Program to find minimum number of deletions required from two ends to make list balanced in Python
- Find minimum number of merge operations to make an array palindrome in C++
- Minimum number of deletions and insertions to transform one string into another using C++.
- Program to count number of minimum swaps required to make it palindrome in Python
- Minimum removal to make palindrome permutation in C++
- Program to count minimum deletions needed to make character frequencies unique in Python
- Program to find minimum number of characters to be added to make it palindrome in Python
- Program to find minimum number of operations to make string sorted in Python
- Counting steps to make number palindrome in JavaScript
Advertisements