POJ1035——Spell checker

来源:互联网 发布:小学生学编程 编辑:程序博客网 时间:2024/06/06 01:38

POJ1035——Spell checker


/************************************************************算法原理:错误有三种情况1)少一个字母2)多一个字母3)其中一个字母被替换①首先,如果|word.length() - dictionary.length()|> 1   就跳过dictionary中的这个单词②因为 string 有 operator== ,可直接比较。如果相等,则flag = 1③都不是以上情况,说明可能是三种情况之一  如果发生不匹配,则根据standard 和checked 的长短确定 谁的 iterator++  因为错误的机会只能是一次Notice:因为程序结构的原因,所有可能匹配的dictionary内的答案储存在了vector里应该是可以优化的************************************************************/#include<iostream>#include<string>#include<vector>using namespace std;vector<string> dictionary ;vector<string> words;void initialize(){string s;while (cin >> s&&s != "#")dictionary.push_back(s);while (cin >> s&&s != "#")words.push_back(s);}bool isCorrect(string standard, string checked, int substract){int difference = 0;auto i = checked.begin(), j = standard.begin();while (i != checked.end() && j != standard.end()){if (*i == *j){i++; j++;}else if (substract == 1){i++; difference++;}else if (substract == -1){j++; difference++;}else if (substract == 0){difference++;i++; j++;}}return difference > 1 ? false : true;}void compare(){int substract = 0, flag = 0;vector<string> correct;for (auto i = words.begin(), j = dictionary.begin(); i != words.end(); i++){flag = 0;for (j = dictionary.begin(); j != dictionary.end(); j++){substract = (*i).length() - (*j).length();if (substract > 1 || substract < -1)//不进入比较continue;if ((*i) == (*j)){flag = 1;break;//注意continue和break的差别}else if (isCorrect((*j), (*i), substract)){flag = 2;correct.push_back(*j);//可能的答案进入vector}}if (flag == 1)cout << *i << " is correct\n";else if (flag == 2){cout << *i << ": ";for (auto i : correct)cout << i << " ";cout << endl;correct.clear();}else cout << *i << " : " << endl;}}int main(){initialize();compare();}


0 0
原创粉丝点击