

- 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
Delete Operations for Two Strings in C++
Suppose we have two words w1 and w2, we have to find the minimum number of steps required to make w1 and w2 the same, where in each step we can delete one character in either string. So if the input is like “sea” and “eat”, then the output will be 2, because we need to delete ‘s’ from w1, this will be “ea” and delete “t” from “eat” from w2. Then they are the same.
To solve this, we will follow these steps
- n := size of s1, m := size of s2
- add one blank space before the strings s1 and s2, then update the s1 and s2 accordingly
- make one table of size (n + 1) x (m + 1)
- for i := 1 to m
- dp[0, i] := dp[0, i - 1] + 1
- for i := 1 to n
- dp[i, 0] := dp[i – 1, 0] + 1
- for i in range 1 to n
- for j in range 1 to m
- if s1[i] = s2[j]
- dp[i, j] := dp[i – 1, j - 1]
- else dp[i, j] = minimum of dp[i – 1, j] + 1 and dp[i, j - 1] + 1
- if s1[i] = s2[j]
- for j in range 1 to m
- return dp[n, m]
Example(C++)
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int minDistance(string s1, string s2) { int n = s1.size(); int m = s2.size(); s1 = " " + s1; s2 = " " + s2; vector < vector <int> > dp(n + 1, vector <int>(m + 1)); for(int i = 1; i <= m; i++){ dp[0][i] = dp[0][i - 1] + 1; } for(int i = 1; i <= n; i++){ dp[i][0] = dp[i - 1][0] + 1; } for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ if(s1[i] == s2[j]){ dp[i][j] = dp[i - 1][j - 1]; } else{ dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1); } } } return dp[n][m]; } }; main(){ Solution ob; vector<int> v = {1,1,1}; cout << (ob.minDistance("sea", "eat")); }
Input
"sea" "eat"
Output
2
- Related Questions & Answers
- Minimum ASCII Delete Sum for Two Strings in C++
- Minimum number of given operations required to make two strings equal using C++.
- Delete every one of the two strings that start with the same letter in JavaScript
- Comparing two strings in MySQL?
- Compare two Strings in Java
- Comparing two strings in C++
- Math operations for BigDecimal in Java
- What are the different operations performed on strings in TOC?
- Differences in two strings in JavaScript
- Compare two strings lexicographically in Java.
- Comparing two Strings lexicographically in Java
- Compare two strings lexicographically in C#
- Concatenation of two strings in PHP
- Difference between two strings JavaScript
- Minimum delete operations to make all elements of array same in C++.
Advertisements