1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
struct letter{
char val;
string word;
letter *next[26];
};
class Dictionary{
letter *root;
void addWord(int pos,string str,letter ** leaf);
bool findWord(int pos, string str,letter* leaf);
public:
void addWord(string str);
bool findWord(string str);
};
/*Private member functions*/
void Dictionary::addWord(string str){
addWord(0,str, &root);
}
bool Dictionary::findWord(string str){
return findWord(0,str,root);
}
/*Public member functions*/
/*Assuming input words are not case sensitive */
void Dictionary::addWord(int pos, string str, letter** leaf){
if (*leaf == NULL){
*leaf= new letter;
(*leaf)->word="";
(*leaf)->val = NULL;
for (int i = 0; i < 26; i++){
(*leaf)->next[i] = NULL;
}
}
if (str.length() == pos){
(*leaf)->word = str;
return;
}
if ((*leaf)->next[(str[pos] - 'a')]==NULL){
letter *temp = new letter;
temp->val = str[pos];
for (int i = 0; i < 26;i++){
temp->next[i] = NULL;
}
temp->word = "";
(*leaf)->next[(str[pos] - 'a')]=temp;
addWord(pos+1,str,&(*leaf)->next[(str[pos]-'a')]);
}
else{
addWord(pos+1,str,&((*leaf)->next[(str[pos]-'a')]));
}
}
bool Dictionary::findWord(int pos,string str,letter* leaf){
if (leaf == NULL){
return false;
}
if (leaf->word.compare(str) == 0){
return true;
}
else{
if (leaf->val == str[pos]){
return findWord(pos+1, str,leaf->next[(str[pos] - 'a')]);
}
else{
if (leaf->next[str[pos] - 'a'] == NULL)
return false;
else{
return findWord(pos+1,str,leaf->next[(str[pos]-'a')]);
}
}
}
}
int main(){
Dictionary d1;
string temp;
ifstream file;
file.open("words.txt");
while (!file.eof()){
file >> temp;
transform(temp.begin(),temp.end(),temp.begin(),tolower);
d1.addWord(temp);
}
cout << "Enter the word to be searched:" << endl;
cin >> temp;
cout << "The answer is " << d1.findWord(temp)<<endl;
cin.ignore();
getchar();
return 0;
}
|