博客园 首页 私信博主 显示目录 隐藏目录 管理

最长公共子串

利用二维数组进行求解

 1 ```
 2 /*求最长公共子串*/
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<cstring>
 6 #include<cstdlib>
 7 using namespace std;
 8 const int maxn=10000;
 9 
10 
11 int main(){
12     int p1;//记录最长公共子串末位置
13     string arr1,arr2;//两个子串
14     getline(cin,arr1);
15     getline(cin,arr2);
16     int temp[arr1.length()][arr2.length()];//声明一个二维数组,存储最长公共子串长度
17     int length=0;//最长公子串长度
18     for(int i=0; i<arr1.length(); i++ ){
19         for(int j=0; j<arr2.length(); j++ ){
20             if(arr1[i]==arr2[j]){
21                 if(i>0&&j>0){
22                     temp[i][j]=temp[i-1][j-1]+1;
23                 }
24                 else{
25                     temp[i][j]=1;
26                 }
27                 if(temp[i][j]>length){//当前元素值大于公共子串长度
28                     length=temp[i][j];
29                     p1=i;
30                 }
31             }
32             else{
33                 temp[i][j]=0;
34             }
35         }
36     }
37     int k;
38     for(k=p1-length+1; k<=p1; k++ ){
39         cout<<arr1[k];
40     }
41     cout<<endl;
42     cout<<length<<endl;
43     return 0;
44 }
45 
46 ```

 

posted @ 2019-01-27 11:12  Brave_WTZ  阅读(169)  评论(0编辑  收藏  举报