forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathls.cpp
138 lines (115 loc) · 2.81 KB
/
ls.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
131
132
133
134
135
136
137
138
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
void print(deque<char> word) {
for(auto i : word) {
cout << i;
}
cout << endl;
}
void str_to_deque(string& s, deque<char>& d) {
for(auto i : s) {
d.push_back(i);
}
}
void deque_to_str(string& s, deque<char>& d) {
for(auto i : d) {
s.push_back(i);
}
}
bool solve(deque<char> pattern, deque<char> word) {
// Strip beginning and end of extra chars
while(!pattern.empty() && !word.empty() && pattern.front() == word.front()) {
pattern.pop_front();
word.pop_front();
}
while(!pattern.empty() && !word.empty() && pattern.back() == word.back()) {
pattern.pop_back();
word.pop_back();
}
// Return true if there are no stars and it worked
if(pattern.empty() && word.empty()) {
return true;
}
// If the pattern is empty and the word is not, it failed
if(pattern.empty()) {
return false;
}
// If there's no word, check that the pattern is all stars
if(word.empty()) {
bool all_stars = true;
for(auto i : pattern) {
if(i != '*') {
all_stars = false;
}
}
return all_stars;
}
// Debugging print
//print(pattern);
//print(word);
// Check if the end values don't match
if(pattern.front() != '*' || pattern.back() != '*') {
return false;
}
// Build an array of patterns to find in the string
vector<string> v_temp;
for(auto i : pattern) {
if(i == '*') {
v_temp.push_back("");
}
else {
v_temp[v_temp.size()-1].push_back(i);
}
}
// Remove empty strings
vector<string> v;
for(auto i : v_temp) {
if(i != "") {
v.push_back(i);
}
}
// Convert the word to a string
string s = "";
deque_to_str(s, word);
// Check that all the search patterns exist
int start = 0;
for(auto i : v) {
// If we're going to overstep, quit
if(start >= s.size()) {
return false;
}
// Find the next match
int loc = s.find(i, start);
// If no match, quit
if(loc == -1) {
return false;
}
// This is the new starting spot
start = loc + i.size();
}
return true;
}
int main() {
// Read in pattern
string p;
cin >> p;
// Convert pattern
deque<char> pattern;
str_to_deque(p, pattern);
// Test each word
int n;
cin >> n;
for(int i = 0; i < n; i++) {
// Read in word
string temp;
cin >> temp;
deque<char> word;
str_to_deque(temp, word);
// If it works, print it
if(solve(pattern, word)) {
print(word);
}
}
}