算法期中 最长公共子串

Problem:

给定两个字符串x = x­1x­2…x­n和y = y­1y­2…ym, 请找出x和y的最长公共子串的长度,也就是求出一个最大的k,使得存在下标i和j有x­ix­i+1…x­i+k-1 = yjy­j+1…y­j+k-1.

x和y只含有小写字母,长度均在1和1000之间.

请为下面的Solution类实现解决上述问题的函数longestSubstring,函数的参数x和y为给出的两个单词,返回值为最长公共子串的长度.

class Solution {
public:
int longestSubstring(string x, string y) {
}
};

例1:x = “abcd”, y = “cdef”,返回值为2.

例2:x = “abcabc”, y = “xyz”,返回值为0.

例3:x = “introduction”, y = “introductive”,返回值为10.

Code:

// Problem#: 21106
// Submission#: 5206587
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
class Solution {
public:
    int longestSubstring(string x, string y) {
        int dp[1001][1001] = {0};
        int Maxlength = 0;
        if (x.size() == 0 || y.size() == 0)
            return 0;
        for (int i = 0; i < x.size(); i++) {
            for (int j = 0; j < y.size(); j++) {
                if(x[i] == y[j]) {
                    if (i != 0 && j != 0) {
                        dp[i][j] = dp[i-1][j-1] + 1;
                    }
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    }
                }
                else {
                    dp[i][j] = 0;
                }
                Maxlength = max(dp[i][j], Maxlength);
            }
        }
        return Maxlength;
    }
};                                 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值