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.验证

  • 相关阅读:
    hmac模块
    hashlib模块
    内存监控
    在全局对象(不是指针)的构造函数里不要对std集合做太多操作
    Lucene 4.X 倒排索引原理与实现
    Git工作流指南
    Spring cloud 框架 --- Eureka 心得
    分布式 的理解
    集群的理解
    Thrift框架-安装
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/9018911.html
Copyright © 2011-2022 走看看