๐ 1143. ๆ้ฟๅ ฌๅ ฑๅญๅบๅ
2022ๅนด6ๆ9ๆฅๅฐไบ 1 ๅ้
๐ 1143. ๆ้ฟๅ ฌๅ ฑๅญๅบๅ
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
// ๆ่ทฏ:
// dp[i][j] = dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + 1
int rows = text1.length();
int cols = text2.length();
int[][] dp = new int[rows + 1][cols + 1];
// ๅๅงๅ
int res = 0;
// dp
for(int i = 1; i <= rows; i ++) {
for(int j = 1; j <= cols; j ++) {
int m = i - 1;
int n = j - 1;
if(text1.charAt(m) == text2.charAt(n)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
res = Math.max(dp[i][j], res);
}
}
return res;
}
}