Day55(392, 115)

392. Is Subsequence

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

Input: s = “abc”, t = “ahbgdc”
Output: true

Example 2:

Input: s = “axc”, t = “ahbgdc”
Output: false

class Solution {  
    public boolean isSubsequence(String s, String t) {  
        int length1 = s.length(); int length2 = t.length();  
        int[][] dp = new int[length1+1][length2+1];  
        for(int i = 1; i <= length1; i++){  
            for(int j = 1; j <= length2; j++){  
                if(s.charAt(i-1) == t.charAt(j-1)){  
                    dp[i][j] = dp[i-1][j-1] + 1;  
                }else{  
                    dp[i][j] = dp[i][j-1];  
                }  
            }  
        }  
        return dp[length1][length2] == length1;  
    }  
}

115. Distinct Subsequences

Given two strings s and t, return the number of distinct

subsequences

of s which equals t.

The test cases are generated so that the answer fits on a 32-bit signed integer.

Example 1:

Input: s = “rabbbit”, t = “rabbit”
Output: 3
Explanation:
As shown below, there are 3 ways you can generate “rabbit” from s.
**rabb**b**it**
**ra**b**bbit**
**rab**b**bit**

Example 2:

Input: s = “babgbag”, t = “bag”
Output: 5
Explanation:
As shown below, there are 5 ways you can generate “bag” from s.
**ba**b**g**bag
**ba**bgba**g**
**b**abgb**ag**
ba**b**gb**ag**
babg**bag**

class Solution {  
    public int numDistinct(String s, String t) {  
        int[][] dp = new int[s.length() + 1][t.length() + 1];  
        for (int i = 0; i < s.length() + 1; i++) {  
            dp[i][0] = 1;  
        }  
  
        for (int i = 1; i < s.length() + 1; i++) {  
            for (int j = 1; j < t.length() + 1; j++) {  
                if (s.charAt(i - 1) == t.charAt(j - 1)) {  
                    dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];  
                }else{  
                    dp[i][j] = dp[i - 1][j];  
                }  
            }  
        }  
  
        return dp[s.length()][t.length()];  
    }  
}

你可能感兴趣的:(leetcode刷题,leetcode,算法,动态规划)