字符串匹配问题编程实现在单词表中查找与已知单词最接近的单词1 如果单词表中有要查找的单词输出该单词的位置2 如果单词表中没有要查找的单词输出与要查找的单词最接近的单词(可能不止一个)。最接近的单词是指以下三种情况a) 两个单词仅仅相差一个字母包括多一个或者少一个字母。如question 和 queston;time 和 timee;b) 两个单词中仅有两个字母位置是相反的。如:teacherhe和taecherc) 两个单词仅有一个字母不同如hello和hallo。这题其实分两部分1️⃣如果单词表里有该单词 → 输出位置2️⃣如果没有 → 找最接近的单词“最接近”有3种情况① 相差一个字母增/删例如question queston或time timee判断方法长度差 1② 两个字母位置互换例如teacher taecher判断恰好两个位置不同 且交换后相同③ 只有一个字母不同例如hello hallo判断长度相同 只有1个字符不同一、解题思路步骤输入单词表 输入待查单词① 先查是否完全相同如果找到输出位置② 如果没有找到遍历单词表判断三种接近情况二、C实现#includeiostream#includevector#includestringusingnamespacestd;booloneReplace(string a,string b){if(a.size()!b.size())returnfalse;intcnt0;for(inti0;ia.size();i)if(a[i]!b[i])cnt;returncnt1;}booloneInsert(string a,string b){if(abs((int)a.size()-(int)b.size())!1)returnfalse;string sa.size()b.size()?a:b;string ta.size()b.size()?b:a;inti0,j0,cnt0;while(is.size()jt.size()){if(s[i]t[j]){i;j;}else{cnt;i;}}returncnt1;}boolswapTwo(string a,string b){if(a.size()!b.size())returnfalse;vectorintpos;for(inti0;ia.size();i)if(a[i]!b[i])pos.push_back(i);if(pos.size()!2)returnfalse;returna[pos[0]]b[pos[1]]a[pos[1]]b[pos[0]];}intmain(){vectorstringword{teacher,hello,time,question,apple};string target;cintarget;for(inti0;iword.size();i){if(word[i]target){cout位置:iendl;return0;}}cout最接近的单词:endl;for(string w:word){if(oneReplace(w,target)||oneInsert(w,target)||swapTwo(w,target)){coutwendl;}}return0;}三、运行示例单词表teacher hello time question apple输入taecher输出最接近的单词: teacher输入hallo输出最接近的单词: hello输入time输出位置:2