Aim: Write a program to check whether a string include Keyword or not.
#include <bits/stdc++.h>
using namespace std;
int countkeywords = 0;
unordered_map<string, int> m;
void LPSArray(string pattern, int M, int* lps) {
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(string pattern, string txt) {
int M = pattern.length();
int N = txt.length();
int lps[M];
LPSArray(pattern, M, lps);
int i = 0;
int j = 0;
while ((N - i) >= (M - j)) {
if (pattern[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
countkeywords++;
m[pattern]++;
j = lps[j - 1];
} else if (i < N && pattern[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
int main() {
string keywords[48] = {"asm", "double", "new", "switch", "auto", "else", "operator", "template",
"break", "enum", "private", "this", "case", "extern", "protected", "throw",
"catch", "float", "public", "try", "char", "for", "register", "typedef",
"class", "friend", "return", "union", "const", "goto", "short", "unsigned",
"continue", "if", "signed", "virtual", "default", "inline", "sizeof", "void",
"delete", "int", "static", "volatile", "do", "long", "struct", "while"};
string text, s;
cout << "Enter String :" << endl;
getline(cin, s);
while (s != "-1") {
text += s;
getline(cin, s);
}
for (int i = 0; i < 48; i++) {
KMPSearch(keywords[i], text);
}
cout << endl;
cout << "Total keywords : " << countkeywords << endl;
for (auto i : m) {
cout << "Keyword " << i.first << " has frequency : " << i.second << endl;
}
return 0;
}

Comments
Post a Comment