题目链接:https://vjudge.net/contest/124428#problem/A
题目大意:
给出两个字符串,求其最长公共子序列的长度。
最长公共子序列算法详解:https://blog.csdn.net/hrn1216/article/details/51534607 (其中的图解很详细) 根据图解理解下面代码
#include<cstdio> #include <string> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int map[1005][1005]; string str1, str2; int len1, len2; int main() { while (cin >> str1 >> str2) { len1 = str1.length(); len2 = str2.length(); for (int i = 0; i <= len1; i++) { for (int j = 0; j <= len2; j++) { if (i == 0 || j == 0) { map[i][j] = 0; continue; } //初始化,将第一行和第一列全部初始化为0 if (str1[i - 1] == str2[j - 1]) map[i][j] = map[i - 1][j - 1] + 1; else map[i][j] = max(map[i - 1][j], map[i][j - 1]); } } printf("%d ", map[len1][len2]); } return 0; }
2018-04-29