注意:因为开的空间是length+1的,对于字符串的下标计算要-1
class Solution { public: /* * @param A: A string * @param B: A string * @return: The length of longest common subsequence of A and B */ int longestCommonSubsequence(string &A, string &B) { // write your code here int length1 = A.length(); int length2 = B.length(); vector<vector<int> > result(length1+1,vector<int>(length2+1)); for(int i = 0;i <= length1;i++) result[i][0] = 0; for(int j = 0;j <= length2;j++) result[0][j] = 0; for(int i = 1;i <= length1;i++){ for(int j = 1;j <= length2;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[length1][length2]; } };