1.
输入3个子串, 输出这3个子串的最大公共子串 。
#include<iostream>
#include<vector>
#include<set>
using namespace std;
//求两个子串的最大公共子串,子串是连续的;
set<string> getcomstring(string s1,string s2){
int m=s1.size(),n=s2.size();
int dp[m+1][n+1];
int ans=0;
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
if(i==0||j==0)
dp[i][j]=0;
else if(s1[i-1]==s2[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
ans=max(ans,dp[i][j]);
}
else
dp[i][j]=0;
}
}
set<string> sub;
if(ans==0)
return sub;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(dp[i][j]==ans){
sub.insert(s1.substr(i-dp[i][j],dp[i][j]));
}
}
}
return sub;
}
int main(){
string s1,s2,s3;
cin>>s1>>s2>>s3;
//先找出s1与s2的公共子串
set<string> a1=getcomstring(s1,s2),ans;
set<string>::iterator it=a1.begin();
//遍历,分别求子串与S3的公共子串
int maxlength=0;
for(it;it!=a1.end();it++){
set<string> temp=getcomstring(*it,s3);
if(!temp.empty()){
set<string>::iterator iter=temp.begin();
while(iter!=temp.end()){
string str=*iter;
//该子串更长,将之前的删除,
if(str.size()>maxlength){
ans.clear();
ans.insert(*iter);
maxlength=str.size();
}//一样长则加入
else if( maxlength==str.size()){
ans.insert(*iter);
}
iter++;
}
}
}
set<string>::iterator itans=ans.begin();
cout<<"最长公共子串有:"<<endl;
while(itans!=ans.end()){
cout<<*itans<<endl;
itans++;
}
return 0;
}
2.
输入树的中序和后序排列,输出树的层次遍历
#include<iostream>
//#include<vector>
#include<string>
#include<queue>
#include<unordered_map>
using namespace std;
pair<string,string> node;
int main(){
// 中序和后序
string mid,right;
cin>>mid>>right;
queue<pair<string,string>> q;
unordered_map<char,int> mp;
for(int i=0;i<right.size();i++){
mp[right[i]]=i;
}
pair<string,string> p(mid,right);
q.push(p);
while(q.size()){
string s1=q.front().first;
string s2=q.front().second;
q.pop();
int n=s1.size();
for(int i=0;i<n;i++){
if(s1[i]==s2[n-1]){
cout<<s1[i];
if(i!=0){
//左子树入队
p.first=s1.substr(0,i);
p.second=s2.substr(0,i);
q.push(p);
}
if(i!=n-1){
//右子树入队
p.first=s1.substr(i+1,n-i-1);
p.second=s2.substr(i,n-i-1);
q.push(p);
}
break;
}
}
}
return 0;
}