思路
1、考慮從後往前推導,隨着字符串的變長,兩個字符串的最後一個字符相同或者不同,對最長公共子序列的長度影響。
2、使用arr[i][j]表示text1的前i個字符和text2的前j個字符的最長公共子序列長度,得到以下狀態轉移方程:
若text1的第i個字符和text2的第j個字符相同,則
arr[i][j] = arr[i - 1][j - 1] + 1;
否則
arr[i][j] = Math.max(arr[i][j - 1], arr[i - 1][j]);
3、考慮二維數組每次循環的時候只有最後一行數據纔有作用,前面已經計算過的已無效,可以優化成一維數組。
4、考慮邊界問題,可以在兩個字符串前面追加“#”,防止邊界越界,不要判斷邊界是否大於0,提升效率。
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
m++;
n++;
int[] arr = new int[n];
char[] arr1 = ("#" + text1).toCharArray();
char[] arr2 = ("#" + text2).toCharArray();
int temp;
int now;
for (int i = 1; i < m; i++) {
temp = 0;
for (int j = 1; j < n; j++) {
now = arr[j];
if (arr1[i] == arr2[j]) {
arr[j] = temp + 1;
} else {
arr[j] = Math.max(arr[j - 1], arr[j]);
}
temp = now;
}
}
return arr[n - 1];
}
}