思路就是为单词表建立一个hash表,对于输入的一个文件,对于他的每一个单词检查是不是在hash表中,如果在这个单词就是正确的,不在就是错误
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <ctype.h>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>
using namespace std;
typedef long long int LL;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int maxn = 1024;
struct data{string word; data *next;};
data *hash_table[maxn];
int change(string s){//把string转换成int
int key = 0;
for (int i = 0; i < s.length(); i++){
key = key * 3 + s[i];
}
return key;
}
int get_hashcode(int k){//乘法散列法
double A = 0.618033;
return floor((k*A - floor((k*A))) * (1 << 10));
}
bool search_hash_table(string word){
int k = change(word);
int code = get_hashcode(k);
data *p = hash_table[code], *q = NULL;
while (p){
if (p->word == word) return true;
else{
q = p;
p = p->next;
}
}//没找到,要把这一项插入到hash表中
data *p1 = new data();
p1->word = word;
p1->next = NULL;
if (!q)//hash表中之前code这一项没有元素
hash_table[code] = p1;
else{
p1->next = hash_table[code];
hash_table[code] = p1;
}
}
void f(string& word){//其实还有很多情况没有判别,因为这道题的精华是hash,那些特殊情况没必要花时间一个一个找出
if (isupper(word[0]))//首字母大写改成小写
word[0] = word[0] - 'A' + 'a';
char ch = word[word.length() - 1];//尾部有符号就删去
if (!islower(ch) && !isupper(ch))
word.erase(word.end() - 1);
ch = word[0];
if (!islower(ch) && !isupper(ch))//首部有符号就删去
word.erase(word.begin());
if (word == "is" || word == "are" || word == "was" || word == "were")//特判
word = "be";
}
int main()
{
ifstream fin1("dictionary.txt");
string word;
while (fin1 >> word)
search_hash_table(word);
fin1.close();
ifstream fin2("paper.txt");
ofstream fout("cout.txt");
int cnt = 0;
while (fin2 >> word){
f(word);
if (!search_hash_table(word)){
cnt++;
fout << word << endl;
}
}
fout << "没出现过的单词总共有" << cnt << "个" << endl;
fin2.close();
fout.close();
return 0;
}