-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_pattern_matching.cpp
103 lines (98 loc) · 2.03 KB
/
string_pattern_matching.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
#include <iostream>
#include <vector>
using namespace std;
bool isPatternMatching(string pattern, string input)
{
vector<int> base;
vector<int> inputBase;
char currentChar = pattern[0];
int currentCharCount = 0;
for (int i = 0; i < pattern.size(); i++)
{
if (pattern[i] != currentChar)
{
base.push_back(currentCharCount);
currentChar = pattern[i];
currentCharCount = 1;
}
else
{
currentCharCount++;
}
if (i == pattern.size() - 1)
{
if (pattern[i] != currentChar)
{
currentCharCount = 1;
}
base.push_back(currentCharCount);
}
}
currentChar = input[0];
currentCharCount = 0;
for (int i = 0; i < input.size(); i++)
{
if (input[i] != currentChar)
{
inputBase.push_back(currentCharCount);
if (inputBase[inputBase.size() - 1] != base[inputBase.size() - 1])
{
return false;
}
currentChar = input[i];
currentCharCount = 1;
}
else
{
currentCharCount++;
}
if (i == input.size() - 1)
{
if (input[i] != currentChar)
{
currentCharCount = 1;
}
inputBase.push_back(currentCharCount);
if (inputBase[inputBase.size() - 1] != base[inputBase.size() - 1])
{
return false;
}
}
}
if (inputBase.size() != base.size())
{
return false;
}
return true;
}
vector<string> findMatchedWords(vector<string> dict, string pattern)
{
vector<string> result;
for (string x : dict)
{
if (isPatternMatching(pattern, x))
{
result.push_back(x);
}
}
return result;
}
int main()
{
cout << "Enter array length" << endl;
int n;
cin >> n;
vector<string> s(n);
cout << "Enter array elements one by one" << endl;
for (int i = 0; i < n; i++)
cin >> s[i];
string tt;
cout << "Enter string pattern to match" << endl;
cin >> tt;
vector<string> res = findMatchedWords(s, tt);
sort(res.begin(), res.end());
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
cout << endl;
return 0;
}