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


一:解题思路

方法一:暴力破解法

方法二:动态规划

二:完整代码示例 (C++版和Java版)

方法一C++:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;


string findLCS(string s1, string s2)
{
    string result = "";
    for (int i = 0; i < s1.size(); i++)
    {
        string temp = "";
        for (int j = 0; j < s2.size(); j++)
        {
            int k = i;
            while (s1[k] == s2[j])
            {
                temp += s1[k];
                k++;
                j++;
            }

            if (temp.size() > result.size())
                result = temp;
            temp = "";
        }
    }

    return result;
}

int main()
{
    string s1 = "";
    string s2 = "";

    while (cin >> s1 >> s2)
    {
        if (s1.size() > s2.size())
            swap(s1,s2);

        string result = findLCS(s1,s2);
        cout << result << endl;
    }

    return 0;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM