zoukankan      html  css  js  c++  java
  • Longest Common String

    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.

    Analyse:

    1. We can use brute force to solve this problem. Start from A[0...lengthA], to B[0...lengthB], if there is a character of the same, check its following and update the result.

    Runtime: 19ms

     1 class Solution {
     2 public:    
     3     /**
     4      * @param A, B: Two string.
     5      * @return: the length of the longest common substring.
     6      */
     7     int longestCommonSubstring(string &A, string &B) {
     8         // write your code here
     9         int lengthA = A.size(), lengthB = B.size();
    10         if (!lengthA || !lengthB) return 0;
    11         
    12         int result = 0;
    13         for (int i = 0; i < lengthA; i++) {
    14             for (int j = 0; j < lengthB; j++) {
    15                 if (A[i] == B[j]) {
    16                     int count = 1;
    17                     while (i + count < lengthA && j + count < lengthB && A[i + count] == B[j + count]) {
    18                         count++;
    19                     }
    20                     result = max(result, count);
    21                 }
    22             }
    23         }
    24         return result;
    25     }
    26 };

    2. We can use dynamic programming to solve this problem. Suppose dp[i][j] is the longest common substring from A[0...i-1] and B[0...j-1]. If A[i] == B[j], then dp[i + 1][j + 1] = dp[i][j] + 1; else, dp[i + 1][j + 1] = 0.

    Runtime: 19ms

     1 class Solution {
     2 public:    
     3     /**
     4      * @param A, B: Two string.
     5      * @return: the length of the longest common substring.
     6      */
     7     int longestCommonSubstring(string &A, string &B) {
     8         // write your code here
     9         int lengthA = A.size(), lengthB = B.size();
    10         if (!lengthA || !lengthB) return 0;
    11         
    12         vector<vector<int> > dp(lengthA + 1, vector<int>(lengthB + 1, 0));
    13         int result = INT_MIN;
    14         for (int i = 0; i < lengthA; i++) {
    15             for (int j = 0; j < lengthB; j++) {
    16                 if (A[i] == B[j]) {
    17                     dp[i + 1][j + 1] = dp[i][j] + 1;
    18                     result = max(result, dp[i + 1][j + 1]);
    19                 }
    20             }
    21         }
    22         return result;
    23     }
    24 };
  • 相关阅读:
    后缀数组
    网络流 HOJ1087
    备用
    css-具有缩略图的材料列表
    正则匹配log行
    vue-cli的webpack打包,icon无法正确加载
    导出CSV,导出excel数字过长显示科学计数法解决方案
    js导出CSV
    git常见操作指令
    javascript原型的意义
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5794562.html
Copyright © 2011-2022 走看看