zoukankan      html  css  js  c++  java
  • 最长公共子串

    利用二维数组进行求解

     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 ```
    有些目标看似很遥远,但只要付出足够多的努力,这一切总有可能实现!
  • 相关阅读:
    STL中的string
    STL中的map
    STL中的set和multiset
    C++基础知识
    希尔排序
    桶排序
    归并排序
    堆排序
    数组左边奇数右边偶数算法O(n)
    背包问题 洛谷P1164 小A点菜
  • 原文地址:https://www.cnblogs.com/Bravewtz/p/10325846.html
Copyright © 2011-2022 走看看