Skip to content

Instantly share code, notes, and snippets.

@izanbf1803
Last active April 24, 2017 16:02
Show Gist options
  • Save izanbf1803/02cb9d29b1888210eee8536068009533 to your computer and use it in GitHub Desktop.
Save izanbf1803/02cb9d29b1888210eee8536068009533 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
using namespace std;
bool less_than(
const string& a,
int ai,
int bi,
int size
){
while (ai < size and bi < size) {
if (a[ai] != a[bi]) return a[ai] < a[bi];
ai++;
bi++;
}
return true;
}
int main()
{
string a, b;
int max, index;
//vector<vector<int>> subs(501, vector<int>(501));
int subs[501][501];
while (cin >> a >> b) {
max = index = 0;
for (int i = 0; i <= a.size(); i++) {
subs[i][0] = 0;
}
for (int j = 0; j <= b.size(); j++) {
subs[0][j] = 0;
}
for (int i = 1; i <= a.size(); i++) {
for (int j = 1; j <= b.size(); j++) {
if (a[i - 1] == b[j - 1]) {
subs[i][j] = subs[i - 1][j - 1] + 1;
if (subs[i][j] > max) {
max = subs[i][j];
index = i - max;
}
else if (subs[i][j] == max and less_than(a, i - max, index, a.size())) {
index = i - max;
}
}
else subs[i][j] = 0;
}
}
for (int i = index; i < index + max; i++) {
cout << a[i];
}
cout << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment