尋找最長公共子串

原文鏈接:https://blog.csdn.net/qq_25800311/article/details/81607168

 

#include<iostream>
#include<string>
#include<vector>
using namespace std;

class Solution {
public:
	string getLCS(string str1, string str2) {
		vector<vector<int>> record(str1.length(), vector<int>(str2.length()));
		int max_len = 0, max_end = 0;
		for (int i = 0; i < str1.length(); ++i) {
			for (int j = 0; j < str2.length(); ++j) {
				if (str1[i] == str2[j]) {//如果想等
					if (i == 0 || j == 0)//如果在邊界
						record[i][j] = 1;
					else//否則爲左上角的+1
						record[i][j] = record[i - 1][j - 1] + 1;
				}
				else
					record[i][j] = 0;//如果不等
				if (record[i][j] > max_len) {//更新max_len和max_end
					max_len = record[i][j];
					max_end = i;
				}
			}
			
		}
		//最後根據max_len和max_end獲取最長公共子串
		return str1.substr(max_end - max_len + 1, max_len);
	}
};
int main() {
	Solution* ptr = new Solution();
	string str = ptr->getLCS("acbcbcef", "abcbced");
	cout << str << endl;
	while (1);

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章