寻找最长公共子串

#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);

}

发布了107 篇原创文章 · 获赞 125 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/Li_haiyu/article/details/100714354
今日推荐