LCS: An Easy LCS
This is an interesting LCS dp for problem for beginner. There is many solution for this problem. In problem this firstly we calculate the size of LCS using recursively.
- string A, B;
- int n, m;
- int dp[102][102];
- int lcs(int i, int j)
- {
- if (i == n + 1 || j == m + 1) {
- return 0;
- }
- if (dp[i][j] != -1) return dp[i][j];
- int x = 0;
- if (A[i] == B[j]) {
- x = lcs(i + 1, j + 1) + 1;
- }
- else {
- x = max(lcs(i + 1, j), lcs(i, j + 1));
- }
- dp[i][j] = x;
- return x;
- }
Then we start to use a to z for getting lexicographically smallest LCS. First we try to use a whether a is the part of LCS and then b and so on. For more clear to you code is given.
- for (int i = 0; i < k; i++) {
- for (int j = 'a'; j <= 'z'; j++) {
- ck = 0;
- x = a;
- while (A[x]) {
- if (A[x] == j) {
- ck++;
- break;
- }
- x++;
- }
- y = b;
- while (B[y]) {
- if (B[y] == j) {
- ck++;
- break;
- }
- y++;
- }
- if (ck == 2) {
- if (dp[a][b] == dp[x][y]) {
- res += A[x];
- a = x + 1;
- b = y + 1;
- break;
- }
- }
- }
- }
Comments
Post a Comment