题解 | #Coincidence#

Coincidence

http://www.nowcoder.com/practice/f38fc44b43cf44eaa1de407430b85e69

/*
描述
Find a longest common subsequence of two strings.
输入描述:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出描述:
For each case, output k – the length of a longest common subsequence in one line.
*/

#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main() {
    string strA;
    string strB;
    cin >> strA;
    cin >> strB;
    int n = strA.size(), m = strB.size();
    int** dp = new int* [n+1];
    for (int i = 0; i < n+1; ++i) {
        dp[i] = new int[m+1] {0};
    }
    for (int i = 1; i < n + 1; ++i) {
        for (int j = 1; j < m + 1; ++j) {
            if (strA[i - 1] == strB[j - 1]) {
            // 此时A,B串同时往后移动一位,此为贪心解法,不过此时贪心即为最优解 (optimal solution)
                dp[i][j] = dp[i - 1][j - 1] + 1;        
            }
            else {
            // 此时最大值为以下二者之一:1. A往后移动一位,B不动;2.B往后移动一位,A不动 (因为A[i-1], B[j]和 A[i], B[j-1]均可能匹配,而A[i],B[j]一定不匹配)
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);        
            }
        }
    }
    cout << dp[n][m]<<endl;

    for (int i = 0; i < n + 1; ++i) {
        delete [] dp[i];
    }
    delete [] dp;

    return 0;
}
全部评论

相关推荐

gelmanspar...:奖学金删掉,自我评价删掉,简历压缩一下,写一页
如果再来一次,你还会学机...
点赞 评论 收藏
分享
10-10 11:38
已编辑
湖南理工大学 Java
小浪_Coding:多沟通叭, 公式简历+学历一般的话难找
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务