給定兩個字符串,輸出最長相同子串:
方法1:暴力破解
#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>
#include<string>
using namespace std;
string lagestcommonsubset(const string &a,const string &b){
int max_length=0;
string res;
for(int i=0;i<a.length();i++){
for(int j=0;j<b.length();j++){
int pos1=i;
int pos2=j;
int length=0;
while(pos1<a.length()&&pos2<b.length()){
if(a[pos1]==b[pos2])
{
pos1++;pos2++;
length++;
}
else{
if(length>max_length){
max_length=length;
res=a.substr(i,length);
}
length=0;
break;
}//else
}//while
if(length>max_length){
max_length=length;
res=a.substr(i,length);
}
}//for
}//for
return res;
}
int main(){
string a,b;
cout<<"輸入兩個字符串,可以包含空格:"<<endl;
getline(cin,a);
getline(cin,b);
cout<<lagestcommonsubset(a,b);
}
(2)動態規划,空間復雜度為O(n2),時間復雜度為O(n2),算法思想:a的第i+1個位置結尾的子串和b的第j+1個位置結尾的子串最大相同長度為a的以位置i結尾和b的以位置j結尾的最大相同子串長度+1,狀態轉移式為dp[i+1,j+1]=dp[i,j]+1。
#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>
#include<string>
using namespace std;
string lagestcommonsubset(const string &a,const string &b){
int m=a.length(),n=b.length();
vector<vector<int>>dp(m+1,vector<int>(n+1,0));
int max_len=0,pos=-1;
for(int i=0;i<a.length();i++){
for(int j=0;j<b.length();j++){
if(a[i]==b[j]){
dp[i+1][j+1]=dp[i][j]+1;
if(dp[i+1][j+1]>max_len){
max_len=dp[i+1][j+1];
pos=i;
}
}
}
}//for
return a.substr(pos-max_len+1,max_len);
}
int main(){
string a,b;
cout<<"輸入兩個字符串,可以包含空格:"<<endl;
getline(cin,a);
getline(cin,b);
cout<<lagestcommonsubset(a,b);
}
(3)動態規划:空間復雜度為O(n),時間復雜度為O(n2),思想同方法2,但是只用一個一維數組來存儲字符串b的每個位置j結尾與當前字符串a的位置i結尾的最大相同子串長度,如求b對應a的以位置i+1結尾的最大相同子串長度時,對b的位置j從后往前求取當前對應a的位置i+1的最大子串長度,當更新到位置j+1時,位置j的值dp[j]為b的位置j結尾對應a的位置i結尾的最大相同子串長度。狀態轉移公式為:dp[j+1]=dp[j]+1,注意,若a[i+1]和b[j+1]不同,則令dp[j+1]=0,不然dp[j+1]會是對應a[i]結尾的最大相同子串長度。
#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>
#include<string>
using namespace std;
string lagestcommonsubset(const string &a,const string &b){
int m=a.length(),n=b.length();
vector<int>dp(n+1);
int max_len=0,pos=-1;
for(int i=0;i<a.length();i++){
for(int j=b.length()-1;j>=0;j--){
if(a[i]==b[j]){
dp[j+1]=dp[j]+1;
if(dp[j+1]>max_len){
max_len=dp[j+1];
pos=j;
}
}
else{
dp[j+1]=0;
}
}
}//for
return b.substr(pos-max_len+1,max_len);
}
int main(){
string a,b;
cout<<"輸入兩個字符串,可以包含空格:"<<endl;
getline(cin,a);
getline(cin,b);
cout<<lagestcommonsubset(a,b);
}