Computer >> Máy Tính >  >> Lập trình >> C ++

Số lần xóa và chèn tối thiểu để biến đổi một chuỗi này thành chuỗi khác bằng C ++.

Mô tả

Cho hai chuỗi str1 và str2 có kích thước lần lượt là m và n. Nhiệm vụ là xóa và chèn một số ký tự tối thiểu từ / trong str1 để biến nó thành str2.

Str1 = “tutorialspoint”
Str2 = “tutorials”
To transform str1 to str2 we have to delete five characters i.e.
“point” from str1.

Thuật toán

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)

Ví dụ

#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;
}

Đầu ra

Khi bạn biên dịch và thực thi chương trình trên. Nó tạo ra kết quả sau -

Min deletion = 5
Min insertion = 0