版权声明:本文为博主原创文章,未经博主允许不得转载,欢迎留言。 https://blog.csdn.net/qq_15046309/article/details/82631698
描述
现在有一些英语单词需要做拼写检查,你的工具是一本词典。需要检查的单词,有的是词典中的单词,有的与词典中的单词相似,你的任务是发现这两种情况。单词A与单词B相似的情况有三种:
1、删除单词A的一个字母后得到单词B;
2、用任意一个字母替换单词A的一个字母后得到单词B;
3、在单词A的任意位置增加一个字母后得到单词B。
你的任务是发现词典中与给定单词相同或相似的单词。
输入
第一部分是词典中的单词,从第一行开始每行一个单词,以"#"结束。词典中的单词保证不重复,最多有10000个。
第二部分是需要查询的单词,每行一个,以"#"结束。最多有50个需要查询的单词。
词典中的单词和需要查询的单词均由小写字母组成,最多包含15个字符。输出
按照输入的顺序,为每个需要检查的单词输出一行。如果需要检查的单词出现在词典中,输出“?x is correct",?x代表需要检查的单词。如果需要检查的单词没有出现在词典中,则输出"?x: ?x1 ?x2 ...?xn",其中?x代表需要检查的单词,?x1...?xn代表词典中与需要检查的单词相似的单词,这些单词中间以空格隔开。如果没有相似的单词,输出"?x:"即可。
样例输入
i is has have be my more contest me too if award # me aware m contest hav oo or i fi mre #样例输出
me is correct aware: award m: i my me contest is correct hav: has have oo: too or: i is correct fi: i mre: more me
试题分析:这个题目还是比较简单的
- 首先接受数据,用两个string数组即可。
- 判断是否有完全相同的情况,先全过一遍,如果有,那么直接输出,开始下一个。
- 如果没有,那么看与词典单词的长度差是否在1之内。超过1就不可能匹配成功。
- 恰好在1之内,分为0和绝对值1两种情况。
- 当为0时,看看从哪里开始字母不相等了,把那个不相等的换掉之后在判断,如果还不相等说明不匹配,相等了就匹配了。
- 当绝对值为1时,先把这两个字符串副本排个序,看看那个比较长的字符串多了那个字符。
- 对比两个字符换,在短字符串与长字符串不相等的那个位置,插入多的那个字符。判断两字符串是否相等,相等就匹配了。
#include<iostream> #include<string> #include<algorithm> #include<cmath> using namespace std; bool IsSame(string a, string b) { char drop; //a短 int mi = min(a.length(), b.length()); string a1 = a; string b1 = b; sort(a1.begin(),a1.end()); sort(b1.begin(), b1.end()); bool exis = false; for (int i = 0; i < mi; i++) { if (a1[i] != b1[i]) { drop = b1[i]; exis = true; break; } } if (!exis) { drop = b1[b1.length() - 1]; } string ti; bool ex = false; for (int i = 0; i < a.length(); i++) { if (a[i]!=b[i]) { ex = true; ti = a.substr(0, i); ti = ti + drop; ti = ti + a.substr(i, 1000); break; } } if (!ex) { ti =a+ drop; } if (ti!=b) { return false; } else { return true; } } int main() { string dictionary[10010]; string words[60]; string a, b; int dic = 0; int m = 0; while (1) { cin >> a; if (a=="#") { break; } else { dictionary[dic++] = a; } } while (1) { cin >>b; if (b == "#") { break; } else { words[m++] = b; } } for (int i = 0; i <m; i++) { bool you = false; for (int j = 0; j < dic; j++) { if (dictionary[j]==words[i]) { cout << words[i] << " is correct" << endl; you = true; break; } }//判断是否完全相同。 if (you != true) { cout << words[i] << ": "; for (int j = 0; j < dic; j++) { int somewhat = words[i].length() - dictionary[j].length(); if (somewhat == 0) { for (int k = 0; k < words[i].length(); k++) { if (words[i][k] != dictionary[j][k]) { string tishen = words[i]; tishen[k] = dictionary[j][k]; if (tishen == dictionary[j]) { cout << dictionary[j] << " "; } } } } if (abs(somewhat) == 1) { if (words[i].length() > dictionary[j].length()) { if (IsSame(dictionary[j], words[i])) { cout << dictionary[j] << " "; } } else { if (IsSame(words[i], dictionary[j])) { cout << dictionary[j] << " "; } } } } cout << endl; } } system("pause"); }