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 };
  • 相关阅读:
    《构建之法》阅读笔记4
    团队冲刺第七天
    团队冲刺第六天
    团队冲刺第五天
    团队冲刺第四天
    团队冲刺第三天
    构建之法阅读笔记03
    第十四周进度条
    第二阶段冲刺站立会议10
    第二阶段冲刺站立会议09
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5794562.html
Copyright © 2011-2022 走看看