【动态规划】记录每日LeetCode 判断子序列 Java实现

题目描述:

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。

初始代码:

class Solution {
    public boolean isSubsequence(String s, String t) {

    }
}

示例1:

输入:s = "abc", t = "ahbgdc"
输出:true

示例2:

输入:s = "axc", t = "ahbgdc"
输出:false

参考答案:

//第一种做法 双指针
//时间复杂度:O(s.length() + t.length())
//空间复杂度:O(1) 
class Solution {
    public boolean isSubsequence(String s, String t) {
        int point = 0;
        for(int i = 0; i < t.length() && point < s.length(); ++i){
            if(s.charAt(point) == t.charAt(i)) point++;
        }
        if(point == s.length()) return true;
        return false;
    }
}
//第二种官方解法:动态规划
class Solution {
    public boolean isSubsequence(String s, String t) {
        int son = s.length(), m = t.length();
        int[][] dp = new int[m + 1][26];

        //初始化边界条件,dp[i][j] = m表示t中不存在字符
        for (int i = 0; i < 26; ++i) {
            dp[m][i] = m;
        }

        for (int i = m - 1; i >= 0; --i) {
            for (int j = 0; j < 26; ++j) {
                if (t.charAt(i) == j + 'a') dp[i][j] = i;
                else dp[i][j] = dp[i + 1][j];
            }
        }

        int j = 0;
        for (int i = 0; i < son; ++i) {
            //t中没有s[i]
            if (dp[j][s.charAt(i) - 'a'] == m) return false;
            //否则直接跳到t中s[i]第一次出现的位置的后一位
            j = dp[j][s.charAt(i) - 'a'] + 1;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_65563175/article/details/130322818