Tag:

在Rabin-Karp滚动哈希

我正在尝试使用Rabin-Karp来寻找子串; 而且我被困在滚动哈希(试图使用维基百科中建议的公式 )。 #define MOD 1000000007 unsigned long long rolling_hash(const char *str) { unsigned long long hash = 0; size_t str_len = strlen(str); for(int i = 0, k = str_len -1; i < str_len; i++, k–) { hash = hash + str[i] * pow(257, k); // hash = hash % MOD; } return hash; } […]

在C中使用linux wc命令计算文件的单词

我正在尝试编写类似于Linux命令wc的东西,以计算任何类型文件中的单词,新行和字节,我只能使用C函数读取。 我写了这段代码,我得到了换行符和字节的正确值,但我得不到计数单词的正确值。 int bytes = 0; int words = 0; int newLine = 0; char buffer[1]; int file = open(myfile,O_RDONLY); if(file == -1){ printf(“can not find :%s\n”,myfile); } else{ char last = ‘c’; while(read(file,buffer,1)==1){ bytes++; if(buffer[0]==’ ‘ && last!=’ ‘ && last!=’\n’){ words++; } else if(buffer[0]==’\n’){ newLine++; if(last!=’ ‘ && last!=’\n’){ words++; } } last […]