文本编辑距离

题目:给定一个字符串word。再给定n个字符串s1, s2, ... sn.

求出s中和word相似度最小的字符串。


注意:两个字符串的相似度是,修改s1或s2的中的任一字符,一次只能改一次,或者是在s1或s2的任一位置增加一个字符,一次只能增加一次。是的最后s1 = s2.

比如:helo -> hea。相似度为2。步骤分别是去掉o, 改变l。


分析:设f[i, j] 表示 word(0, i) 和 s(0, j)的文本相似度。

那么 f[i, j] = min(f[i, j-1] + 1, f[i - 1, j], f[i - 1, j - 1] + (word[i] == s[j]? 0: 1));

min中的三个方程的意思分别是:

   s(0, j-1),添加一个s[j],

   word(0, i-1) 添加一个word[i],

   word[i] == s[j]?想的话则由f[i-1, j-1]决定,不相等则修改word[i]或者s[j] 再加上 f[i- 1, j-1]。

#include <cstring>

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

#define MAXN 100

int arr[MAXN][MAXN];

int dp(const string &s1, const string &s2, int i, int j) {
    if (i == -1 && j == -1) {
        return 0;
    } else if (i == -1) {
        return j + 1;
    } else if (j == -1) {
        return i + 1;
    }

    if (arr[i][j] >= 0) {
        return arr[i][j];
    }

    int mn = dp(s1, s2, i - 1, j) + 1;
    mn = min(mn, dp(s1, s2, i, j - 1) + 1);
    mn = min(mn ,dp(s1, s2, i-1, j - 1) + (s1[i] == s2[j]? 0: 1));

    arr[i][j] = mn;

    return mn;
}

int main() {
    string word;
    cin >> word;
    int n;
    cin >> n;
    vector<string> dict(n);
    for (int i = 0; i < n; i++) {
        cin >> dict[i];
    }

    vector<int> dist(n);
    int mn = (1 << 30);
    for (int i = 0; i < n; i++) {
        memset(arr, -1, sizeof(arr));
        dist[i] = dp(word, dict[i], word.size() - 1, dict[i].size() - 1);
        if (dist[i] < mn) {
            mn = dist[i];
        }
    }

    for (int i = 0; i < n; i++) {
//        cout << dist[i] << " ";
        if (dist[i] == mn) {
            cout << dict[i] << " ";
       }
    }
    cout << endl;

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值