1. 程式人生 > >求兩個字串的最大匹配

求兩個字串的最大匹配

給定兩個字串,例如 abceafg 和bcaedeafgabcea,求出它們兩個最大的公有字串,此題的解為最大長度是5,abcea。

程式碼如下:

#include<iostream>
#include<string>

using namespace std;
int main()
{
	string str1, str2;
	getline(cin, str1);
	getline(cin, str2);
	int maxL = 0, c = 0;
	int t = 0;
	for (int i = 0; i<str1.size()&&t<str1.size(); i++) {
		auto re = str2.find(str1[i]);
		while (re != string::npos) {
			t = i;
			int b = re;
			while (t<str1.size() && re<str2.size() && str1[t] == str2[re]) {
				++t;
				++re;
			}
			if (maxL<t - i) {
				c = i;
				maxL = t - i;
			}
			if (b<str2.size() - 1) {
				re = str2.find(str1[i],b+1);
			}
			else {
				break;
			}
			if (t == str1.size()) {
				break;
			}
		}
	}
	cout << maxL << endl;
	cout << str1.substr(c, maxL) << endl;
	return 0;
}