首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何获取最长公用子串的索引?

获取最长公共子串的索引可以通过动态规划算法来实现。具体步骤如下:

  1. 创建一个二维数组dp,大小为两个字符串的长度加1,用于记录最长公共子串的长度。
  2. 初始化dp数组的第一行和第一列为0。
  3. 遍历两个字符串的每个字符,如果两个字符相等,则将dp[i][j]设置为dp[i-1][j-1] + 1,表示当前字符是最长公共子串的一部分。
  4. 同时,记录最长公共子串的长度maxLen和最长公共子串的结束索引endIndex。
  5. 遍历完所有字符后,最长公共子串的起始索引为endIndex - maxLen + 1。

以下是一个示例代码:

代码语言:txt
复制
def longest_common_substring(s1, s2):
    m, n = len(s1), len(s2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    maxLen = 0
    endIndex = 0

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
                if dp[i][j] > maxLen:
                    maxLen = dp[i][j]
                    endIndex = i - 1

    startIndex = endIndex - maxLen + 1
    return startIndex, endIndex

s1 = "abcdefg"
s2 = "defgxyz"
startIndex, endIndex = longest_common_substring(s1, s2)
print("最长公共子串的索引范围:[{}, {}]".format(startIndex, endIndex))

这段代码的输出结果为:最长公共子串的索引范围:[3, 6],表示最长公共子串为"defg",起始索引为3,结束索引为6。

腾讯云相关产品和产品介绍链接地址:

  • 云服务器(ECS):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版(CDB):https://cloud.tencent.com/product/cdb
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 腾讯云存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云区块链服务(TBC):https://cloud.tencent.com/product/tbc
  • 腾讯云元宇宙(Tencent XR):https://cloud.tencent.com/product/xr
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券