返回介绍

Longest Common Substring

发布于 2025-02-22 13:01:22 字数 1894 浏览 0 评论 0 收藏 0

Source

Given two strings, find the longest common substring.
Return the length of it.

Example
Given A="ABCD", B="CBCE", return 2.
Note
The characters in substring should occur continuously in original string.
This is different with subsequence.

题解

求最长公共子串,注意「子串」和「子序列」的区别!简单考虑可以使用两根指针索引分别指向两个字符串的当前遍历位置,若遇到相等的字符时则同时向后移动一位。

C++

class Solution {
public:
  /**
   * @param A, B: Two string.
   * @return: the length of the longest common substring.
   */
  int longestCommonSubstring(string &A, string &B) {
    if (A.empty() || B.empty()) {
      return 0;
    }

    int lcs = 0, lcs_temp = 0;
    for (int i = 0; i < A.size(); ++i) {
      for (int j = 0; j < B.size(); ++j) {
        lcs_temp = 0;
        while ((i + lcs_temp < A.size()) &&\
             (j + lcs_temp < B.size()) &&\
             (A[i + lcs_temp] == B[j + lcs_temp]))
        {
          ++lcs_temp;
        }

        // update lcs
        if (lcs_temp > lcs) {
          lcs = lcs_temp;
        }
      }
    }

    return lcs;
  }
};

源码分析

  1. 异常处理,空串时返回 0.
  2. 分别使用 ij 表示当前遍历的索引处。若当前字符相同时则共同往后移动一位。
  3. 没有相同字符时比较此次遍历的 lcs_templcs 大小,更新 lcs .
  4. 返回 lcs .

注意在 while 循环中不可直接使用 ++i 或者 ++j ,因为有可能会漏解!

复杂度分析

双重 for 循环,最坏时间复杂度约为 O(mn⋅lcs)O(mn \cdot lcs)O(mn⋅lcs).

Reference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文