跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:392.判断子序列
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
- 本题直接转换为:求
s
和t
的最长相等子序列长度,然后再将最长相等子序列的长度和s.length()
作比较即可,如果相等则返回true
,否则返回false
- 参考:最长公共子序列
java"> public boolean isSubsequence(String s, String t) {char[] c1 = s.toCharArray();char[] c2 = t.toCharArray();int[][] dp = new int[c1.length + 1][c2.length + 1];for (int i = 1; i <= c1.length; i++) {for (int j = 1; j <= c2.length; j++) {if (c1[i - 1] == c2[j - 1]) {dp[i][j] = dp[i - 1][j - 1] + 1;} else {dp[i][j] = dp[i][j - 1];}}}return dp[c1.length][c2.length] == c1.length ? true : false;}