class Solution {
public boolean isSubsequence(String s, String t) {
int n1 = s.length();
int n2 = t.length();
char[] ch1 = s.toCharArray();
char[] ch2 = t.toCharArray();
// 1.确定dp数组,二维数组 dp[i][j] 以i-1为结尾的和以j-1为结尾的最长公共子序列
int[][] dp = new int[n1+1][n2+1];
// 2.确定递推关系
/**
if(ch1[i-1] == ch2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
*/
int result = 0;
// 3.初始化 都为0
// 4.遍历顺序,从小到大遍历
for(int i=1; i<=n1; i++){
for(int j=1; j<=n2; j++){
if(ch1[i-1] == ch2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
result = Math.max(result,dp[i][j]);
}
}
return result == n1;
}
}
运行结果: