zoukankan      html  css  js  c++  java
  • LeetCode 1143 最长公共子序列

    链接:https://leetcode-cn.com/problems/longest-common-subsequence

    给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列。

    一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
    例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。

    若这两个字符串没有公共子序列,则返回 0。

    示例 1:

    输入:text1 = "abcde", text2 = "ace"
    输出:3
    解释:最长公共子序列是 "ace",它的长度为 3。
    示例 2:

    输入:text1 = "abc", text2 = "abc"
    输出:3
    解释:最长公共子序列是 "abc",它的长度为 3。
    示例 3:

    输入:text1 = "abc", text2 = "def"
    输出:0
    解释:两个字符串没有公共子序列,返回 0。

    提示:

    1 <= text1.length <= 1000
    1 <= text2.length <= 1000
    输入的字符串只含有小写英文字符。

    这道题用动态规划的方法来解,我们开一个二维数组 dp[i][j] 来存储状态,表示text1的前i个字符与text2的前j个字符的最长公共子序列。那么它的值应当有如下情况。

    如果text1的第i个字符与text2的第j个字符相同,那么dp[i][j] = dp[i-1][j-1] + 1

    如果text1的第i个字符与text2的第j个字符不同,那么dp[i][j] = max(dp[i-1][j] , dp[i][j-1]). 因为已经知道第i个和第j个完全不同了,所以不用让它们都往前走了,只让text2走到j,或者只让text1走到i,就足够了。然后比较哪种结果最大,因为求的是最长公共子序列嘛,所以取最大值。

    状态的转变就是这样,要注意的是,因为下标会取到dp[i-1][j-1],所以在循环时要从1开始,而不是0.

    c++代码如下:

     1 class Solution {
     2 public:
     3     int longestCommonSubsequence(string text1, string text2) {
     4         vector<vector<int>> dp(text1.length() + 1, vector<int>(text2.length() + 1));
     5         for(int i = 1; i < text1.length() + 1; i++){
     6             for(int j = 1; j < text2.length() + 1; j++){
     7                 if(text1[i-1] == text2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
     8                 else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
     9             }
    10         }
    11         return dp.back().back();  
    12     }
    13 };
  • 相关阅读:
    faster with MyISAM tables than with InnoDB or NDB tables
    w-BIG TABLE 1-toSMALLtable @-toMEMORY
    Indexing and Hashing
    MEMORY Storage Engine MEMORY Tables TEMPORARY TABLE max_heap_table_size
    controlling the variance of request response times and not just worrying about maximizing queries per second
    Variance
    Population Mean
    12.162s 1805.867s
    situations where MyISAM will be faster than InnoDB
    1920.154s 0.309s 30817
  • 原文地址:https://www.cnblogs.com/hellosnow/p/12090920.html
Copyright © 2011-2022 走看看