File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
problems/dynamic_programming
tests/dynamic_programming Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ class DistinctSubsequences :
2
+ @staticmethod
3
+ def numDistinct (s : str , t : str ) -> int :
4
+ # Lengths of both strings
5
+ m , n = len (s ), len (t )
6
+ # Lookup table to store count of distinct subsequences
7
+ lookup = [[0 for j in range (n + 1 )] for i in range (m + 1 )]
8
+ # If t is empty, it can be subsequence of every string but only once
9
+ for i in range (m + 1 ):
10
+ lookup [i ][0 ] = 1
11
+ # If both strings are empty
12
+ lookup [0 ][0 ] = 1
13
+ # Populate the remaining table
14
+ for j in range (1 , n + 1 ):
15
+ for i in range (1 , m + 1 ):
16
+ lookup [i ][j ] = lookup [i - 1 ][j ]
17
+ # If characters are same
18
+ if s [i - 1 ] == t [j - 1 ]:
19
+ lookup [i ][j ] += lookup [i - 1 ][j - 1 ]
20
+ return lookup [m ][n ]
Original file line number Diff line number Diff line change
1
+ import unittest
2
+
3
+ from problems .dynamic_programming .distinct_subsequences import DistinctSubsequences
4
+
5
+
6
+ class TestDistinctSubsequences (unittest .TestCase ):
7
+
8
+ def setUp (self ):
9
+ self .distinct_subsequences = DistinctSubsequences ()
10
+
11
+ def test_num_distinct_empty_strings (self ):
12
+ self .assertEqual (self .distinct_subsequences .numDistinct ("" , "" ), 1 )
13
+
14
+ def test_num_distinct_empty_target (self ):
15
+ self .assertEqual (self .distinct_subsequences .numDistinct ("abc" , "" ), 1 )
16
+
17
+ def test_num_distinct_empty_source (self ):
18
+ self .assertEqual (self .distinct_subsequences .numDistinct ("" , "abc" ), 0 )
19
+
20
+ def test_num_distinct_same_strings (self ):
21
+ self .assertEqual (self .distinct_subsequences .numDistinct ("abc" , "abc" ), 1 )
22
+
23
+ def test_num_distinct_general_cases (self ):
24
+ self .assertEqual (self .distinct_subsequences .numDistinct ("babgbag" , "bag" ), 5 )
25
+ self .assertEqual (self .distinct_subsequences .numDistinct ("rabbbit" , "rabbit" ), 3 )
26
+ self .assertEqual (self .distinct_subsequences .numDistinct ("abc" , "def" ), 0 )
27
+
28
+
29
+ if __name__ == "__main__" :
30
+ unittest .main ()
You can’t perform that action at this time.
0 commit comments