参考代码随想录算法训练营第五十五天 |392. 判断子序列、115. 不同的子序列 - 掘金
class Solution:def isSubsequence(self, s: str, t: str) -> bool:start = 0 #used to make sure that the relative positions do not changefor char in s:t = t[start:]idx = t.find(char)if idx == -1:return Falsestart = idx + 1return True
class Solution(object):def isSubsequence(self, s, t):""":type s: str:type t: str:rtype: bool"""pointerS = 0pointerT = 0while pointerT < len(t):if pointerS >= len(s):breakif t[pointerT] == s[pointerS]:pointerS += 1pointerT += 1return pointerS == len(s)
五部曲:
1. 确定dp数组以及下标的含义:
dp[i][j] 表示以下标i-1为结尾的字符串s,和以下标j-1为结尾的字符串t,相同。序列的 长度为dp[i][j]。
2. 确定递推公式:
首先要考虑如下两种操作:
- if (s[i - 1] == t[j - 1]):也就是t中找到了一个字符在s中也出现了。那么dp[i][j] = dp[i - 1][j - 1] + 1;,因为找到了一个相同的字符,相同子序列长度自然要在dp[i-1][j-1]的基础上加1
- if (s[i - 1] != t[j - 1]):也就是相当于t要删除元素,继续匹配。t如果把当前元素t[j - 1]删除,那么dp[i][j] 的数值就是看s[i - 1]与 t[j - 2]的比较结果了,即:dp[i][j] = dp[i][j - 1];
3. dp数组如何初始化:从递推公式可以看出dp[i][j]都是依赖于dp[i - 1][j - 1] 和 dp[i][j - 1], 所。以dp[0][0]和dp[i][0]是一定要初始化的。dp[i][0] 表示以下标i-1为结尾的字符串,与空字符串的相同子序列长度,所以为0. dp[0][j]同理。
(这里大家已经可以发现,在定义dp[i][j]含义的时候为什么要表示以下标i-1为结尾的字符 串s,和以下标j-1为结尾的字符串t,相同子序列的长度为dp[i][j]。因为这样的定义在dp二 维矩阵中可以留出初始化的区间。如果要是定义的dp[i][j]是以下标i为结尾的字符串s和以下标j为结尾的字符串t,初始化就比较麻烦了。)
这与#718,#1143和#1035对于dp数组的定义出于同样的目的,都是可以简化初始化过程。二刷时确定一下按照哪个方式来写,固定下来
4. 确定遍历顺序:从递推公式可以看出dp[i][j]都是依赖于dp[i - 1][j - 1] 和 dp[i][j - 1],那么遍历顺序也应该是从上到下,从左到右
5. 打印检查
class Solution(object):def isSubsequence(self, s, t):""":type s: str:type t: str:rtype: bool"""dp = [[0]*(len(t)+1) for _ in range(len(s)+1)]# print(dp)for i in range(1, len(s)+1):for j in range(1, len(t)+1):if s[i - 1] == t[j - 1]:dp[i][j] = dp[i-1][j-1]+1else:dp[i][j] = dp[i][j-1]return dp[len(s)][len(t)] == len(s)
Q:#392在定义dp数组时是dp = [[0]*(len(t)+1) for _ in range(len(s)+1)](
s
is a subsequence oft
);这道题是t is a subsequence of s,dp数组定义也是dp = [[0] * (len(t)+1) for _ in range(len(s)+1)],为什么可以这样?
class Solution(object):def numDistinct(self, s, t):""":type s: str:type t: str:rtype: int"""dp = [[0]*(len(t)+1) for _ in range(len(s)+1)]print(dp)for i in range(len(s)):dp[i][0] = 1for j in range(1, len(t)):dp[0][j] = 0for i in range(1, len(s)+1):for j in range(1, len(t)+1):if s[i-1] == t[j-1]:dp[i][j] = dp[i-1][j-1] + dp[i-1][j]else:dp[i][j] = dp[i-1][j]return dp[len(s)][len(t)]
下一篇:python面向对象(下)