#79 Longest Common Substring

本文介绍了一种寻找两个字符串中最长公共子串的方法,通过构建匹配矩阵并沿对角线检查连续字符来确定最长公共子串的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given two strings, find the longest common substring.

Return the length of it.

 Notice

The characters in substring should occur continuously in original string. This is different with subsequence.

Example

Given A = "ABCD", B = "CBCE", return 2.

Challenge 

O(n x m) time and memory.

题目思路:

这题想到用一个match matrix,去记录每个A[i]和B[j]是否相等。再遍历A和B,当match[i][j]为true的时候,就沿着这一点的右下对角线一直check下去,看相等的char有多少,并记录它的长度为local。取所有这样的local中的最大值就是我们的答案了。

Mycode(AC = 37ms):

class Solution {
public:    
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    int longestCommonSubstring(string &A, string &B) {
        // write your code here
        if (A.size() == 0 || B.size() == 0) return 0;
        
        vector<vector<bool>> match(A.size(), vector<bool>(B.size(), false));
        
        // get the match matrix, indicating whether
        // A[i] == B[j]
        for (int i = 0; i < A.size(); i++) {
            for (int j = 0; j < B.size(); j++) {
                if (A[i] == B[j]) {
                    match[i][j] = true;
                }
            }
        }
        
        int global = 0, local = 0;
        for (int i = 0; i < A.size(); i++) {
            for (int j = 0; j < B.size(); j++) {
                int tmp_i = i, tmp_j = j;
                local = 0;
                
                // check along the 45 degree line
                while (tmp_i < A.size() && tmp_j < B.size() && match[tmp_i][tmp_j]) {
                    local++;
                    tmp_i++;
                    tmp_j++;
                }
                global = max(global, local);
            }
        }
        
        return global;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值