[华为]公共字串计算

链接:https://www.nowcoder.com/questionTerminal/98dc82c094e043ccb7e0570e5342dd1b
来源:牛客网

题目标题:

计算两个字符串的最大公共字串的长度,字符不区分大小写

详细描述:

接口说明

原型:

int getCommonStrLength(char * pFirstStr, char * pSecondStr);

输入参数:

     char * pFirstStr //第一个字符串

     char * pSecondStr//第二个字符串

输入描述:

输入两个字符串


输出描述:

输出一个整数

输入例子:
asdfas werasdfaswer
输出例子:
6

//动态规划 if(a[i]==b[j])c[i][j]=c[i-1][j-1]+1;else c[i][j]=0;



#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include<algorithm>

using namespace std;
int main()
{     
    string str1,str2;    
     while(cin>>str1)    
    {        
        cin>>str2;        
        vector<vector<int> > matrix(str1.size(),vector<int>(str2.size()));        
        int max_num=0;       
        for(int i=0;i<str1.size();i++)        
        {            
            for(int j=0;j<str2.size();j++)            
            {                
                if(str1[i]!=str2[j])                   
                    matrix[i][j]=0;                
                else if(i==0||j==0)                
                {                    
                    matrix[i][j]=1;                    
                    if(max_num<1)                      
                        max_num=1;                
                }                
                else                
                {                   
                    matrix[i][j]=matrix[i-1][j-1]+1;                   
                    if(matrix[i][j]>max_num)                        
                        max_num=matrix[i][j];               
                }           
            }        
        }        
        cout<<max_num<<endl;     
    }   
    return 0;
}
原文地址:https://www.cnblogs.com/hellochennan/p/6669035.html