最长公共子串(动态规划)

[编程题] 最长公共子串

对于两个字符串,请设计一个时间复杂度为O(m*n)的算法(这里的m和n为两串的长度),求出两串的最长公共子串的长度。这里的最长公共子串的定义为两个序列U1,U2,..Un和V1,V2,...Vn,其中Ui + 1 == Ui+1,Vi + 1 == Vi+1,同时Ui == Vi。

给定两个字符串AB,同时给定两串的长度nm

测试样例:
"1AB2345CD",9,"12345EF",7
返回:4
请看我的另一篇博文: 点击打开链接


class LongestSubstring {
public:
    int findLongest(string str1, int n, string str2, int m) {
        // write code here
        int length1 = str1.size() ;
        int length2 = str2.size() ;
        int result = 0 ;
        vector<vector<int>> vec( length1 + 1, vector<int>( length2 + 1, 0 ) ) ;
        for ( int i = 0; i <= length1; ++ i ) {
            for ( int j = 0; j <= length2; ++ j ) {
                if ( i == 0 || j == 0 ) {
                    vec[i][j] = 0 ;
                } else if ( str1[i - 1] == str2[j - 1] ) {
                    vec[i][j] = vec[i - 1][j - 1] + 1 ;
                    result = result > vec[i][j] ? result : vec[i][j] ;
                } else {
                    vec[i][j] = 0 ;
                }
            }
        }
        
        return result ;
    }
};


第二次做:

class LongestSubstring {
public:
    int findLongest(string str1, int n, string str2, int m) {
        // write code here
        vector<vector<int>> vec( str1.size() + 1, vector<int>( str2.size() + 1, 0 ) ) ;
        int result = 0 ;
        for ( int i = 0; i <= str1.size(); ++ i ) {
            for ( int j = 0; j <= str2.size(); ++ j ) {
                if ( i == 0 || j == 0 ) vec[i][j] = 0 ;
                else if ( str1[i - 1] == str2[j - 1] ) {
                    vec[i][j] = vec[i - 1][j - 1] + 1 ;
                    result = result > vec[i][j] ? result : vec[i][j] ;
                } 
                else vec[i][j] = 0 ;
            }
        }
        
        return result ;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值