3.對於狀態的理解,保持最佳的,或者延續最佳的。code
public class LongestCommonSubsequence { public static int compute(char[] str1, char[] str2) { int substringLength1 = str1.length; int substringLength2 = str2.length; int[][] opt = new int[substringLength1 + 1][substringLength2 + 1]; for (int i = substringLength1-1; i >= 0; i--) { for (int j = substringLength2-1; j >= 0; j--) { // System.out.println(i); // System.out.println(j); // System.out.println("-*- "); if (str1[i] == str2[j]) { opt[i][j] = opt[i + 1][j + 1] + 1; } else { opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]); } } } return opt[0][0]; } public static int compute(String str1,String str2){ return compute(str1.toCharArray(),str2.toCharArray()); } public static void main(String[] args){ String a1="abcd"; String a2="bcead"; int l1=compute(a1,a2); System.out.println(l1); } }