
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 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
Advertisements