题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
    string a,b;
    while(cin>>a>>b)
    {
        if(a.length()>b.length())
        {
            string c=a;
            a=b;b=c;
        }
        int h[1000][1000]={0};
        int e=a.length();int f=b.length();
        for(int i=0;i<e;i++)
        {
            for(int j=0;j<f;j++)
            {
               
                for(int m=0;m<min(e-i,f-j);m++)
                {
                    if(a[i+m]==b[j+m])
                    {
                       h[i][j]++; 
                    }
                    else if(a[i+m]!=b[j+m])
                    {
                        break;
                    }
                }
            }
        }
        int n=0;
          for(int i=0;i<e;i++)
        {
            for(int j=0;j<f;j++)
            {
                if(h[i][j]>n)
                {
                    n=h[i][j];
                }
            }
          }
        int g=0;
          for(int i=0;i<e;i++)
        {
                  if(g==1)
                  {
                      break;
                  }
          for(int j=0;j<f;j++) 
            {
                if(h[i][j]==n)
                {
                  cout<<a.substr(i,n);
                    g=1;
                    break;
                }
            }
          }
                       
    }
    return(0);
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务