zoukankan      html  css  js  c++  java
  • 最长公共子串

    题目描述

    对于两个字符串,请设计一个时间复杂度为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
     
     
    我的代码:
        int findLongest(string A, int n, string B, int m) {
            // write code here
            int dp[510][510] = {0};
            int res = 0;
            for(int i = 1; i <= n; i++)
            {
                for(int j = 1; j <= m; j++)
                {
                    if(A[i-1]==B[j-1])
                        dp[i][j] = dp[i-1][j-1]+1;
                    else
                        dp[i][j] = 0;
                    if(dp[i][j] > res)
                        res = dp[i][j];
                }
            }
            return res;
        }

    思路:

    1.设计dp数组

    dp[i][j] 为字符串A以第i个字符为结尾和字符串B以第j个字符为结尾的最大公共子串长度。

    2.设计状态转移方程

    dp[i][j] = dp[i-1][j-1] +1或者dp[i][j] = 0;第i个字符和第j个字符相同则+1;不同则置为0;

    最大公共子串为dp[i][j] 的最大值

    3.确定初始状态

    全部为0

    4.验证

  • 相关阅读:
    构造和析构
    const修饰的成员函数
    class和struct权限
    封装加强
    函数重载实现原理
    Unity2019破解hub
    Lua模拟stack
    函数重载
    LeanTween
    占位参数和默认参数
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/9018911.html
Copyright © 2011-2022 走看看