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

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

cpp 复制代码
#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. 选择最佳匹配:遍历整个字典,找到编辑距离最小的单词作为校正结果。
相关推荐
初圣魔门首席弟子7 小时前
【C++ 学习】单词统计器:从 “代码乱炖” 到 “清晰可品” 的复习笔记
开发语言·c++
十五年专注C++开发7 小时前
CFF Explorer: 一款Windows PE 文件分析的好工具
c++·windows·microsoft
郝学胜-神的一滴7 小时前
计算机图形学中的光照模型:从基础到现代技术
开发语言·c++·程序人生·图形渲染
Lynnxiaowen9 小时前
今天我们开始学习python语句和模块
linux·运维·开发语言·python·学习
深耕AI9 小时前
MFC + OpenCV 图像预览显示不全中断问题解决:GDI行填充详解
c++·opencv·mfc
余辉zmh9 小时前
【C++篇】:ServiceBus RPC 分布式服务总线框架项目
开发语言·c++·rpc
水饺编程9 小时前
第3章,[标签 Win32] :窗口类03,窗口过程函数字段
c语言·c++·windows·visual studio
千里马-horse10 小时前
在android中 spdlog库的log如何在控制台上输出
android·c++·spdlog
橘子是码猴子10 小时前
LangExtract:基于LLM的信息抽取框架 学习笔记
笔记·学习
AnySpaceOne10 小时前
笔记本电脑如何连接打印机?完整连接教程送上
学习·电脑