
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 and Insertions to Transform One String into Another Using C++
Description
Given two strings str1 and str2 of size m and n respectively. The task is to delete and insert a minimum number of characters from/in str1 so as to transform it into str2.
Str1 = “tutorialspoint” Str2 = “tutorials” To transform str1 to str2 we have to delete five characters i.e. “point” from str1.
Algorithm
1. Find longest common subsequence of str1 and str2. Let’s call it as “lcsSize” 2. Number of characters to be deleted = (length of str1 - lcsSize) 3. Number of characters to be inserted = (length of str2 - lcsSize)
Example
#include <iostream> #include <algorithm> using namespace std; int lcs(string s1, string s2, int m, int n){ if (m == 0 || n == 0) { return 0; } if (s1[m - 1] == s2[n - 1]) { return 1 + lcs(s1, s2, m - 1, n - 1); } else { return max(lcs(s1, s2, m, n - 1), lcs(s1, s2, m - 1, n)); } } void minDeletionAndInsertion(string s1, string s2){ int m = s1.size(); int n = s2.size(); int lcsSize = lcs(s1, s2, m, n); cout << "Min deletion = " << (m - lcsSize) << endl; cout << "Min insertion = " << (n - lcsSize) << endl; } int main(){ minDeletionAndInsertion("tutorialspoint", "tutorials"); return 0; }
Output
When you compile and execute the above program. It generates the following output −
Min deletion = 5 Min insertion = 0
Advertisements