C++笔试题 最长公共子串

版权声明:代码属于原创,转载请联系作者并注明出处。 https://blog.csdn.net/weixin_43379056/article/details/83541200

最长公共子串

描述

给出两个字符串,找到最长公共子串,并返回其长度。

输入描述

输入两个任意长度的英文字符串

输出描述

返回公共字符串的长度

样例输入 1

A=“ABCD”,B=“CBCE”

样例输出 1

2

#include <iostream>
#include <string>   // swap()

using namespace std;

class CambrianTest
{
public:
    int getLengthOfLargestCommonSubStr(const string& str1, const string& str2);
};

int CambrianTest::getLengthOfLargestCommonSubStr(const string& str1, const string& str2)
{
    string longerStr(str1);
    string shorterStr(str2);

    if (shorterStr.size() > longerStr.size())
    {
        swap(shorterStr, longerStr);
    }

    if (longerStr.find(shorterStr) != string::npos)
    {
        return shorterStr.size();
    }

    int size = shorterStr.size();

    string largestSubStr = "";
    string subStr;

    for (int i = 0; i < size; i++) // i is start position of sub-str of shorterStr
    {
        for (int j = i+1; j < size; j++) // j is end position of sub-str of shorterStr
        {
            subStr.assign(shorterStr.begin() + i, shorterStr.begin() + j);

            if (longerStr.find(subStr) != string::npos)
            {
                if (largestSubStr.size() < subStr.size())
                {
                    largestSubStr = subStr;
                }
            }
        }
    }
#ifdef UNIT_TEST
    cout << largestSubStr << endl;
#endif

    return largestSubStr.size();
}
    
int main()
{
    string A, B;

    cin >> A >> B;

    CambrianTest ct;

    cout << ct.getLengthOfLargestCommonSubStr(A, B) << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43379056/article/details/83541200