Design and Analysis of Algorithms - edit distance problem


Edit distance problem


description

Let A and B be two strings. Use the least operating character string A string is converted into B. Here characters operations include
(1) delete a character;
(2) inserting a character;
(3) a character to another character.
A string edit distance B is converted into a string of characters used in the minimum number of operations called string A to B, denoted as d (A, B). Try to design an efficient algorithm, for any given two strings A and B, are calculated edit distance d (A, B).
Programming tasks:
For a given string A and string B, edit program to calculate the distance d (A, B).

Entry

The first line of the input data string A, the second line is the character string B.

Export

When the run is finished, the edit distance d (A, B) outputs.

Sample input

fxpimu
xwrs

Sample Output

5

problem analysis:

Two string edit distance seek operation including deletion, insertion, modification. Examples can be found in the law analysis edit distance.
See strings A, B, the length of comparison
(1)如果length(A) > length(B)   
   The delete operation M = length (A) - length (B) times  the number of different character strings A and B is calculated string denoted as N; indicates if the A to B,
   M times required to perform the deletion and modification operations N times. Edit distance d (A, B) = M + N;
(2)
如果length(A) < length(B)  
   The insert operation M = length (B) - length (A) times  the number of different character strings A and B is calculated string denoted as N; indicates if the A to B,
   Inserting operation needs to be performed M times N times and modify operations. Edit distance d (A, B) = M + N;
(3)
如果length(A) = length(B)  
   则直接 计算 B 字符串与 A 字符串 的不同的字符的个数 记为 N;则表明若 A 变为 B,
   需要执行修改操作 N 次。则编辑距离为 d(A,B) = N;


代码:
#include <iostream>
#include <bits/stdc++.h> //万能头文件

using namespace std;

int main()
{
    string a,b;
    int len_a,len_b;
    int diff; // a 和 b 中不同字符的个数
    int editing_distance; // d(a,b) 编辑距离
    int m; // m 为 数组 a 和 b 的长度差

    cin>> a;
    cin>> b;
    len_a = a.length();
    len_b = b.length();
    m =len_a - len_b;

    //cout<<len_a;

    int Mycount=0; //A,B中不相同的字母的个数;

    for(int i=0;i<len_a;i++){
        for(int j=0;j<len_b;j++){
            if(b[j] == a[i])
                Mycount++;
            else
                continue;

        }
    }
   // cout<< Mycount;

   diff = len_b -Mycount; //a 和 b 中不同的字符个数

    if(len_a > len_b)
        { editing_distance = diff + m; }        //m 位正数
    else if(len_a < len_b)
        { editing_distance = diff - m; }  //m 为负数
    else
        editing_distance = diff;

    cout << editing_distance;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_34851243/article/details/78256355