编辑距离\n


给定两个字符串。第一个字符串是源字符串,第二个字符串是目标字符串。在这个程序中,我们必须找出将第一个字符串转换为第二个字符串所需的可能编辑次数。 

字符串的编辑可以是插入一些元素、删除第一个字符串中的内容或修改一些内容以转换为第二个字符串。

输入和输出

Input:
Two strings to compare.
string 1: Programming
string 2: Programs
Output:
Enter the initial string: Programming
Enter the final string: Programs
The number of changes required to convert Programming to Programs is 4

算法

editCount(initStr, finalStr, initLen, finalLen)

输入- 初始字符串和最终字符串及其长度。
输出- 使 initStr 转换为 finalStr 所需的编辑次数。

Begin
   if initLen = 0, then
      return finalLen
   if finalLen := 0, then
      return initLen

   if initStr[initLen - 1] = finalStr[finalLen - 1], then
      return editCount(initStr, finalStr, initLen – 1, finalLen - 1)
   answer := 1 + min of (editCount(initStr, finalStr, initLen , finalLen - 1)),
      (editCount(initStr, finalStr, initLen – 1, finalLen ),
      (editCount(initStr, finalStr, initLen – 1, finalLen - 1)
   return answer
End

示例

#include<iostream>
using namespace std;

int min(int x, int y, int z) {       //find smallest among three numbers
   if(x < y) {
      if(x < z)
         return x;
      else
         return z;
   }else {
      if(y < z)
         return y;
      else
         return z;
   }
}

int editCount(string initStr , string finalStr, int initLen, intfinalLen) {
   if (initLen == 0)       //when initial string is empty, add all characters of final string
      return finalLen;

   if (finalLen == 0)       //when final string is empty, delete all characters from initial string
      return initLen;

   //when last character matches, recursively check previous characters
   if (initStr[initLen-1] == finalStr[finalLen-1])
      return editCount(initStr, finalStr, initLen-1, finalLen-1);

   //if last character match is not found, check for insert, delete and update operations recursively
   return 1 + min ( editCount(initStr, finalStr, initLen, finalLen- 1),  // insert
 
      editCount(initStr, finalStr, initLen-1, finalLen), // delete
      editCount(initStr, finalStr, initLen-1, finalLen-1) // update
   );
}

int main() {
   string initStr;
   string finalStr;

   cout << "Enter the initial string: "; cin >> initStr;
   cout << "Enter the final string: "; cin >> finalStr;
   cout << "The number of changes required to convert " << initStr << " to " << finalStr;
   cout << " is " << editCount( initStr , finalStr, initStr.size(), finalStr.size()) << endl;
}

输出

Enter the initial string: Programming
Enter the final string: Programs
The number of changes required to convert Programming to Programs is 4

更新日期:16-6-2020

1K+ 浏览量

开启你 事业

通过完成课程获得认证

开始
广告