CK016[动态规划]-编辑距离

代码骑士
优质创作者: 游戏开发技术领域
2023-02-09 11:03:05

一、问题描述

 

二、问题重述

 

三、问题分析

 

四、算法设计

 

五、算法图解

 

 

六、伪代码

七、源代码

#include<iostream>
#include<cstring>
using namespace std;
const int N=100;
char str1[N],str2[N];
int d[N][N]; //d[i][j]表示str1前i个字符和str2前j个字符的编辑距离。

int min(int a,int b){
	return a<b?a:b;//返回二者中较小的值 
}

int editdistance(char *str1,char *str2){
	
	int len1 = strlen(str1);//计算字符串长度;
	int len2 = strlen(str2);
	
	for(int i=0; i<=len1; i++) d[i][0]=i;//当第二个串长度为0,编辑距离初始化为i 
	for(int j=0; j<=len2; j++) d[0][j]=j;//当第一个串长度为0,编辑距离初始化为j
	
	for(int i=1;i <=len1;i++)     //遍历两个字符串
    {
        for(int j=1;j<=len2;j++)
        {
            int diff;//判断str[i]是否等于str2[j],相等为0,不相等为1
            if(str1[i-1] == str2[j-1]){ //相等
            	diff = 0 ;
			}else{
            	diff = 1 ;	
			}
            int temp = min(d[i-1][j] + 1, d[i][j-1] + 1);//先两者取最小值
            d[i][j] = min(temp, d[i-1][j-1] + diff);//再取最小值,
            //相当于三者取最小值d[i-1][j] + 1, d[i][j-1] + 1,d[i-1][j-1] + diff
        }
    }
    return d[len1][len2];
} 

int main(){
	cout << "输入字符串str1:"<<endl;
    cin >> str1;
    cout << "输入字符串str2:"<<endl;
    cin >> str2;
    cout << str1<< "和"<<str2<<"的编辑距离是:"<<editdistance (str1,str2);
	return 0;
} 

输出:

 

...全文
246 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

5

社区成员

发帖
与我相关
我的任务
社区描述
考研408:数据结构、计算机组成原理、操作系统、计算机网络
学习方法考研面试 其他
社区管理员
  • 代码骑士
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧