• 两个串中的第一个最长子串


    题目:求两个串中的第一个最长子串(神州数码以前试题)。如"abractyeyt","dgdsaeactyey"的最大子串为"actyey"。

    答:

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    //两个串中的第一个最长子串
    string FindLongestCommonSubString(string strOne, string strTwo)
    {
        if ("" == strOne || strOne.length() <= 0 || "" == strTwo || strTwo.length() <= 0)
        {
            return NULL;
        }
        if (strOne.length() < strTwo.length())  //strOne始终是最长的, 相当于母串,strTwo相当于子串
        {
            string strTmp = strOne;
            strOne = strTwo;
            strTwo = strTmp;
        }
        int *mask = new int[strOne.length()];
        int maxlength = 0;
        int end = -1;
        memset(mask, 0, sizeof(int)*strOne.length());
        for (int i = 0; i < strTwo.length(); i++)
        {
            for (int j = strOne.length() - 1; j >= 0; j--)
            {    
                if (strTwo[i] == strOne[j])
                {
                    if (i == 0 || j == 0)
                    {
                        mask[j] = 1; //母串为第一个元素,或者子串只有一个元素
                    }
                    else
                    {
                        mask[j] = mask[j - 1] + 1;
                    }
                }
                else
                {
                    mask[j] = 0;
                }
                if (mask[j] > maxlength)
                {
                    maxlength = mask[j];
                    end = j;
                }
            }
        }
        delete [] mask;
        return strOne.substr(end - maxlength + 1, maxlength);
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        string strOne = "123456789abcdefghijklmn2131fdfdfdf";
        string strTwo = "123456sdkk123456789abcddkfdfkd123456789abcde";
        cout<<"第一个字符串: "<<strOne<<endl;
        cout<<"第二个字符串: "<<strTwo<<endl;
        cout<<"最长公共子串: "<<FindLongestCommonSubString(strOne, strTwo);
    
        cout<<endl;
        return 0;
    }

    界面运行如下:

  • 相关阅读:
    React 进修之路(1)
    requireJS的配置心得
    DOM的内部插入和外部插入
    h5移动端设备像素比dpr介绍
    原生js--事件类型
    React 进修之路(3)
    javaScript
    html&css
    MyBatis
    Maven基础
  • 原文地址:https://www.cnblogs.com/venow/p/2673010.html
Copyright © 2020-2023  润新知