编辑距离问题(动态规划)

一、问题描述

                设A和B是两个字符串,长度分别为n,m要用最少的字符操作(包括字符的插入、删除、修改),这样的操作称为字符串A到B的操作距离,记为d(A,B)。


#include <iostream>
#include <cstring>
#include <algorithm>
#define MAXN 1000
using namespace std;
int min_three(int a, int b, int c) {
	int temp = min(a, b);
	return min(temp, c);
}
int main() {
	char str1[MAXN], str2[MAXN];
	int num[MAXN][MAXN], i, j, len1, len2;
	while(cin>>str1>>str2) {
		len1 = strlen(str1);
		len2 = strlen(str2);
		for(i = 0; i < len1; i++) {
			num[i][0] = i;
		}
		for(j = 0; j < len2; j++) {
			num[0][j] = j;
		}		
		for(i = 1; i < len1; i++) {
			for(j = 1; j < len2; j++) {
				if(str1[i]==str2[j]) {
					num[i][j] = num[i-1][j-1] + 1;
				} else {
					num[i][j] = min_three(num[i][j-1], num[i-1][j-1], num[i][j-1]) + 1; 
				}
			}
		}
		cout<<num[len1-1][len2-1]<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/adusts/article/details/80387993