diff --git a/src/my_project/interviews/top_150_questions_round_22/ex_141_interleaving_string.py b/src/my_project/interviews/top_150_questions_round_22/ex_141_interleaving_string.py new file mode 100644 index 00000000..dff3c6d8 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_22/ex_141_interleaving_string.py @@ -0,0 +1,16 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + dp = [False] * (n + 1) + dp[0] = True + for j in range(1, n + 1): + dp[j] = dp[j - 1] and s2[j - 1] == s3[j - 1] + for i in range(1, m + 1): + dp[0] = dp[0] and s1[i - 1] == s3[i - 1] + for j in range(1, n + 1): + dp[j] = (dp[j] and s1[i - 1] == s3[i + j - 1]) or \ + (dp[j - 1] and s2[j - 1] == s3[i + j - 1]) + return dp[n] + \ No newline at end of file diff --git a/src/my_project/interviews_typescript/top_150_questions_round_1/ex_141_interleaving_string.ts b/src/my_project/interviews_typescript/top_150_questions_round_1/ex_141_interleaving_string.ts new file mode 100644 index 00000000..19351ca0 --- /dev/null +++ b/src/my_project/interviews_typescript/top_150_questions_round_1/ex_141_interleaving_string.ts @@ -0,0 +1,17 @@ +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length, n = s2.length; + if (m + n !== s3.length) return false; + const dp: boolean[] = new Array(n + 1).fill(false); + dp[0] = true; + for (let j = 1; j <= n; j++) { + dp[j] = dp[j - 1] && s2[j - 1] === s3[j - 1]; + } + for (let i = 1; i <= m; i++) { + dp[0] = dp[0] && s1[i - 1] === s3[i - 1]; + for (let j = 1; j <= n; j++) { + dp[j] = (dp[j] && s1[i - 1] === s3[i + j - 1]) || + (dp[j - 1] && s2[j - 1] === s3[i + j - 1]); + } + } + return dp[n]; +}; \ No newline at end of file diff --git a/tests/test_150_questions_round_22/test_141_interleaving_string_round_22.py b/tests/test_150_questions_round_22/test_141_interleaving_string_round_22.py new file mode 100644 index 00000000..2c816c75 --- /dev/null +++ b/tests/test_150_questions_round_22/test_141_interleaving_string_round_22.py @@ -0,0 +1,24 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_22\ +.ex_141_interleaving_string import Solution + + +class InterleavingStringTestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + + def test_example1(self): + self.assertTrue(self.solution.isInterleave("aabcc", "dbbca", "aadbbcbcac")) + + def test_example2(self): + self.assertFalse(self.solution.isInterleave("aabcc", "dbbca", "aadbbbaccc")) + + def test_empty_strings(self): + self.assertTrue(self.solution.isInterleave("", "", "")) + + def test_wrong_length(self): + self.assertFalse(self.solution.isInterleave("a", "b", "abc")) + + def test_one_empty(self): + self.assertTrue(self.solution.isInterleave("", "abc", "abc")) + self.assertTrue(self.solution.isInterleave("abc", "", "abc")) \ No newline at end of file