-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPugachev_lab№1
122 lines (105 loc) · 2.09 KB
/
Pugachev_lab№1
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
include<iostream>
#include<string>
using namespace std;
const int n = 26;
class trie
{
public:
struct Node
{
char value;
Node *child[n];
} *head;
trie()
{
head = new Node;
head->value = 0;
for ( int i = 0; i < n; i++)
{
head->child[i] = NULL;
}
}
void init(Node *node, char a)
{
node->value = a;
for (int i = 0; i < n; i++)
{
node->child[i] = NULL;
}
}
void insert(string word)
{
Node *current = head;
for (int i = 0; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a';
if (current->child[letter] == NULL)
{
current->child[letter] = new Node;
init(current->child[letter], word[i]);
}
//current->child[letter]->value =word[i];
current = current->child[letter];
}
};
bool noChild(Node* newn)
{
for (int i = 0; i < n; i++)
{
if (newn->child[i])
return 0;
}
return 1;
};
void deleteEven(Node *newr, int i) // функция удаления веток чётной длины
{
int k;
for ( k = 0; k < n; k++)
{
if (newr->child[k] != NULL)
{
deleteEven(newr->child[k], ++i); // вызываем функцию от потомка и удавиваем номер буквы i чтобы потом при удалении всего слова очередная буква была чётной
i *= 2;
}
}
if ((i % 2 == 0)&&(noChild(newr)))
{
delete newr ;
}
};
void newdelete()
{
Node* newr = head;
deleteEven(newr, 0);
};
bool search(string word)
{
Node *current = head;
for (int i = 0; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a';
if ((current->child[letter] == NULL)||(current->child[letter]->value != word[i]))
return 0;
current = current->child[letter];
}
return 1;
};
};
int main()
{
trie Words;
string word;
cout << "Enter words, then enter 0:\n";
do
{
cin >> word;
if (word != "0")
Words.insert(word);
} while (word != "0");
Words.newdelete();
cout << "enter the word to check" << endl;
cin >> word;
(Words.search(word)) ? cout << "yes" : cout << "no";
system("pause");
return 0;
}