Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,
"ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
Here is an example:
S =
S =
"rabbbit"
, T = "rabbit"
Return
3
.Solution:
class Solution: # @return an integer def numDistinct(self, S, T): numberOfSubsequences = [1] positions ={} for i in range (len(T)-1,-1,-1): numberOfSubsequences.append(0) if not T[i] in positions: positions[T[i]]=[] positions[T[i]].append(i) for i in range(0,len(S)): if S[i] in positions: for j in positions[S[i]]: numberOfSubsequences[j+1]+=numberOfSubsequences[j] return numberOfSubsequences[len(T)]
No comments :
Post a Comment