-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubstring-diff.cpp
102 lines (86 loc) · 2.48 KB
/
substring-diff.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
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
/* Separate the string into a vector such that input 0 hello world comes out
example vector<string> i::: i[0] = 0; i[1] = hello; i[2] = world;
*/
vector<string> split(string &str, char c = ' ')
{
vector<string> result;
int start = 0, end = 0;
for (int i = 0; i <= str.size(); i++) {
end++;
if (str[i] == ' ') {
result.push_back(str.substr(start, end - 1));
start = end + start;
end = 0;
}
}
result.push_back(str.substr(start, end)); // Add the last one to the string
return result;
}
int longestRangeMinSub(string P,string Q, int posP, int posQ, int sliceSize, int maxSum) {
int longest = 0, i = 0, runningSum = 0;
while (i + longest < sliceSize) {
if (P[posP + i + longest] != Q[posQ + i + longest]) {
runningSum++;
}
if (runningSum > maxSum) {
if (P[posP + i] != Q[posQ + i]) {
runningSum--;
}
i++;
} else {
longest++;
}
}
return longest;
}
int compareMissMatches(const vector<string> &data) {
int maxMissMatches = atoi(data[0].c_str());
string P = data[1], Q = data[2];
int longest = 0, sliceSize = 0;;
int m = P.length(), n = P.length();
int end1, end2, posP, posQ, longestInSub;
for(int i = 0; i < m + n + 1; i++) {
if (i > n) {
sliceSize = m - (i - n);
} else {
sliceSize = min(i, m);
}
if (sliceSize == 0) {
continue;
}
end1 = max(m, m - i);
if (i > n) {
end1 = m - (i - n);
}
posP = end1 - sliceSize;
end2 = min(i, n);
posQ = end2 - sliceSize;
longestInSub = longestRangeMinSub(P, Q, posP, posQ, sliceSize, maxMissMatches);
longest = max(longest, longestInSub);
}
return longest;
}
int main() {
int numberOfTests;
vector<string> tests;
cin >> numberOfTests;
for (int i = 0;i <= numberOfTests; i++) {
string testLine;
getline(cin, testLine);
if (testLine != "") {
tests.push_back(testLine);
}
}
for (string& test: tests) {
vector<string> delimitedTest = split(test);
cout << compareMissMatches(delimitedTest) << endl;
}
return 0;
}