最长公共子序列:
class Solution { public: int findLength(vector<int>& A, vector<int>& B) { int len1 = A.size(); int len2 = B.size(); if(len1 == 0 || len2 == 0) return 0; vector<vector<int>> result(len1+1,vector<int>(len2+1)); for(int i = 0;i <= len1;i++){ result[i][0] = 0; } for(int i = 0;i <= len2;i++){ result[0][i] = 0; } for(int i = 1;i <= len1;i++){ for(int j = 1;j <= len2;j++){ if(A[i-1] == B[j-1]) result[i][j] = result[i-1][j-1] + 1; else result[i][j] = max(result[i-1][j],result[i][j-1]); } } return result[len1][len2]; } };
最长公共子串
class Solution { public: int findLength(vector<int>& A, vector<int>& B) { int len1 = A.size(); int len2 = B.size(); if(len1 == 0 || len2 == 0) return 0; vector<vector<int>> result(len1+1,vector<int>(len2+1)); for(int i = 0;i <= len1;i++){ result[i][0] = 0; } for(int i = 0;i <= len2;i++){ result[0][i] = 0; } for(int i = 1;i <= len1;i++){ for(int j = 1;j <= len2;j++){ if(A[i-1] == B[j-1]) result[i][j] = result[i-1][j-1] + 1; else result[i][j] = 0; } } int maxnum = 0x80000000; for(int i = 1;i <= len1;i++){ for(int j = 1;j <= len2;j++){ if(result[i][j] > maxnum) maxnum = result[i][j]; } } return maxnum; } };
原文地址:https://www.cnblogs.com/ymjyqsx/p/9153166.html
时间: 2024-11-06 07:08:29