最長公共子序列

#include<iostream>
#include<string>

using namespace std;

string LCS(string s1,string s2){
	string ans;
	int i,j;
	int max=0,maxj=0;
	int c[100];
	for(i=0;i<s2.size();i++)
		for(j=s1.size()-1;j>=0;j--){
			if (s1[j] == s2[i]) {
				if (j==0||i==0) {
					c[j]=1;
				}else
					c[j]=c[j-1]+1;
			}else
				c[j]=0;
			if (c[j]>max) {
				max = c[j];
				maxj = j;
			}
		}
		if (max==0) 
			return "";
		for(i=maxj-max+1;i<=maxj;i++){
			ans +=s1[i];
		}

	return ans;
}

int main(){

	string s1 = "sa22aafffffff";
	string s2 = "sa22sdfffffff";
	cout<<LCS(s1,s2)<<endl;
	return 0;
}


發佈了46 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章