图论学习3 c++ 动态规划

使用c++设计一个自动校正英文拼写错误的程序

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>

// 用于纠正拼写错误的函数,基于 Levenshtein 距离
std::string correctWord(const std::string& word, const std::vector<std::string>& dictionary) {
    if (std::find(dictionary.begin(), dictionary.end(), word) != dictionary.end()) {
        return word; // 如果单词已在字典中,直接返回
    }

    std::string bestMatch = word;
    int minDistance = std::numeric_limits<int>::max();

    // 遍历字典,找到最接近的匹配
    for (const auto& dictWord : dictionary) {
        int distance = levenshteinDistance(word, dictWord);
        if (distance < minDistance) {
            minDistance = distance;
            bestMatch = dictWord;
        }
    }

    return bestMatch; // 返回纠正后的单词
}

// 计算两个字符串之间的 Levenshtein 距离
int levenshteinDistance(const std::string& s1, const std::string& s2) {
    std::vector<std::vector<int>> dp(s1.length() + 1, std::vector<int>(s2.length() + 1, 0));

    for (int i = 0; i <= s1.length(); i++) {
        for (int j = 0; j <= s2.length(); j++) {
            if (i == 0) {
                dp[i][j] = j; // 初始化第一行
            } else if (j == 0) {
                dp[i][j] = i; // 初始化第一列
            } else if (s1[i-1] == s2[j-1]) {
                dp[i][j] = dp[i-1][j-1]; // 字符相同,无额外代价
            } else {
                dp[i][j] = 1 + std::min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]}); // 选择最小代价
            }
        }
    }

    return dp[s1.length()][s2.length()]; // 返回最终的 Levenshtein 距离
}

int main() {
    std::vector<std::string> dictionary = {"hello", "world", "programming", "computer", "algorithm"};
    std::string input;
    std::cout << "请输入一个单词:";
    std::cin >> input;
    
    std::string corrected = correctWord(input, dictionary);
    std::cout << "纠正后的单词:" << corrected << std::endl;

    return 0;
}

算法思想:

  1. 字典匹配:首先检查输入的单词是否已经在字典中。如果在,就不需要校正。
  2. 最小编辑距离:如果单词不在字典中,我们使用Levenshtein距离(编辑距离)算法来找到最相似的单词。编辑距离衡量了将一个字符串转换为另一个字符串所需的最少单字符编辑(插入、删除或替换)次数。
  3. 动态规划:Levenshtein距离的计算使用了动态规划方法,这能够有效地解决这个问题,避免重复计算。
  4. 选择最佳匹配:遍历整个字典,找到编辑距离最小的单词作为校正结果。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值