-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpostmid_lab6_trie.cpp
130 lines (107 loc) · 2.62 KB
/
postmid_lab6_trie.cpp
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
123
124
125
126
127
128
129
130
#include<bits/stdc++.h>
using namespace std;
struct NODE {
struct NODE* next[53];
}*NIL;
bool flag;
//check if the string is palindrome or not
bool Pal(string s){
int n = s.length();
for(int i = 0, j = n-1; i < j; ++i, --j) {
if(s[i] != s[j]) return false;
}
return true;
}
class Trie {
NODE *root, *NIL;
NODE* createNode() {
NODE* new_node = new NODE;
for(int i = 0; i < 53; ++i) {
new_node->next[i] = NULL;
}
return new_node;
}
public:
Trie() {
root = createNode();
root->next[52] = NIL;
NIL = createNode();
}
void insert(string s) {
int n = s.length();
NODE *temp = root;
for(int i = 0; i < n; ++i) {
if(islower(s[i])) {
if(temp->next[s[i]-'a']) {
temp = temp->next[s[i]-'a'];
}
else
{
temp->next[s[i]-'a'] = createNode();
temp = temp->next[s[i]-'a'];
}
}
else
{
char c = s[i] + 32;
if(temp->next[c-'a' + 26]) {
temp = temp->next[c-'a' + 26];
}
else
{
temp->next[c-'a'+26] = createNode();
temp = temp->next[c-'a'+26];
}
}
}
temp->next[52] = NIL;
}
bool search(string s) {
int n = s.length();
NODE *temp = root;
for(int i = 0; i < n; ++i) {
if(islower(s[i])) {
if(temp->next[s[i]-'a']) {
temp = temp->next[s[i]-'a'];
} else {
return false;
}
} else
{
char c = tolower(s[i]);
if(temp->next[c-'a' + 26]) {
temp = temp->next[c-'a' + 26];
}
else
{
return false;
}
}
}
return temp->next[52] == NIL;
}
};
int main() {
Trie t;
int n;
cin >> n;
string s[n];
vector<string> NP;
for(int i = 0; i < n; ++i) {
cin >> s[i];
if(!Pal(s[i])) {
t.insert(s[i]);
string r = s[i];
reverse(r.begin(), r.end());
NP.push_back(r);
}
}
for(int i = 0; i < NP.size(); ++i) {
if(t.search(NP[i])) {
printf("YES\n");
break;
}
}
if(!flag) printf("NO\n");
return 0;
}