2017校园招聘编程题——两个字符串中找到最大公共字符串

1. 题目描述

  输入两个字符串,从中找到它们最大的公共子字符串。
  输入描述:
   输入为两行,每行字符串string长度在[1,100]之间。
  输出描述:
   输出公共子字符串。
  输入例子:
   abfeee
   abefdfee
  输出例子:
   fee

2. 解题思路

  匹配两个字符串(str1、str2)中最大公共子字符串(comStr),我们可以想象,最大匹配结果即较长字符串能够全匹配较短字符串,而最小匹配结果除了无一匹配情况,就只能匹配一个字符。这样想就简单许多,首先肯定需要比较字符串长度大小,找到较短字符串作为匹配参考,然后从较短字符串中截取一个字符,一直考虑到截取其全长度字符串,在较长字符串中寻找两者最大公共子字符串。
  思路总结如下:
  Ⅰ输入字符串str1、str2;
  Ⅱ比较出最短字符串(假设为str1,其长度为N),以str1作为匹配参考的字符串;
  Ⅲ从str1中依次截取子字符串长度为len = 1:N
    ⑴ 开始len =1;
    ⑵ 每个截取长度为len的子字符串都在str2中查询,如有匹配赋给comStr;
    ⑶ len = len+1,重复查询,直到len=N结束;
  Ⅳ 输出最终最长子公共字符串comStr。  
例如:
  较短字符串str1为abc:
   len为1匹配字符串:a、b、c
   len为2匹配字符串:ab、bc
   len为3匹配字符串:abc、
   依次在str2查询匹配结果。

3. 程序实现过程:

3.1 Java实现:

package ComString;
import java.util.Scanner;
public class SuitStringAB {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);      
        String str_1 = scan.nextLine();
        String str_2 = scan.nextLine();
        System.out.println(commonString(str_1 ,str_2));
        scan.close();
    }
    public static String commonString(String str1 ,String str2)
    {
        String comString   = "";
        String childString = "";
        String minString   = str1.length() <= str2.length() ? str1 : str2; //寻找较短的字符串
        for( int i=1;i<minString.length();i++)//遍历minString所有的匹配长度
            for( int j=0; j<minString.length();j++)//遍历每个长度下的所有字符串
            {
                if(j+i <= minString.length())
                {
                    childString = minString.substring(j, j+i);
                    if(str2.indexOf(childString) != -1) 
                        comString = childString;                    
                }               
            }
        return comString;       
    }
}

3.2 C/C++实现:

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

int main()
{
    char str1[100],str2[100],comStr[100],tempStr[100];
    cin >>str1>>str2;
    if(strlen(str2)>strlen(str1))
    {   
        swap(str1,str2);//比较字符串大小(algorithm头文件中),小的赋给str2                           
    }
    comStr[0]=0;
    for(int i=0;i<strlen(str2);i++)
       for(int j=strlen(str2);j>i;j--)
    {
        memset(tempStr,0,sizeof(tempStr));
        strncpy(tempStr,str2+i,j-i);
        if(strstr(str1,tempStr))//strstr 为库中匹配子字符串函数
        {
            if(strlen(tempStr)>strlen(comStr))//当匹配到字符串tempStr,和之前comStr比较长度,长者替换短者
                 strcpy(comStr,tempStr);
        }
    }
    cout<<comStr<<endl;

    return 0;
}

  这种方式时间复杂度为O(N²),还有其他时间复杂度低的方法请参考网上其他博客,这里不再详细描述。


个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢!

转载请注明出处:CSDN 无鞋童鞋。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值