forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distinct-subsequences.py
33 lines (30 loc) · 957 Bytes
/
distinct-subsequences.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from __future__ import print_function
# Time: O(n^2)
# Space: O(n)
#
# 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 = "rabbbit", T = "rabbit"
#
# Return 3.
#
class Solution:
# @return an integer
def numDistinct(self, S, T):
ways = [0 for _ in xrange(len(T) + 1)]
ways[0] = 1
for S_char in S:
for j, T_char in reversed(list(enumerate(T))):
if S_char == T_char:
ways[j + 1] += ways[j]
return ways[len(T)]
if __name__ == "__main__":
S = "rabbbit"
T = "rabbit"
result = Solution().numDistinct(S, T)
print(result)