diff --git a/src/my_project/interviews/top_150_questions_round_22/ex_134_word_break.py b/src/my_project/interviews/top_150_questions_round_22/ex_134_word_break.py new file mode 100644 index 00000000..622704dd --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_22/ex_134_word_break.py @@ -0,0 +1,14 @@ +from typing import List + +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + word_set = set(wordDict) + n = len(s) + dp = [False] * (n + 1) + dp[0] = True + for i in range(1, n + 1): + for j in range(i): + if dp[j] and s[j:i] in word_set: + dp[i] = True + break + return dp[n] \ No newline at end of file diff --git a/src/my_project/interviews_typescript/top_150_questions_round_1/ex_134_word_break.ts b/src/my_project/interviews_typescript/top_150_questions_round_1/ex_134_word_break.ts new file mode 100644 index 00000000..42f4314f --- /dev/null +++ b/src/my_project/interviews_typescript/top_150_questions_round_1/ex_134_word_break.ts @@ -0,0 +1,15 @@ +function wordBreak(s: string, wordDict: string[]): boolean { + const wordSet = new Set(wordDict); + const n = s.length; + const dp: boolean[] = new Array(n + 1).fill(false); + dp[0] = true; + for (let i = 1; i <= n; i++) { + for (let j = 0; j < i; j++) { + if (dp[j] && wordSet.has(s.substring(j, i))) { + dp[i] = true; + break; + } + } + } + return dp[n]; +} \ No newline at end of file diff --git a/tests/test_150_questions_round_22/test_134_word_break_round_22.py b/tests/test_150_questions_round_22/test_134_word_break_round_22.py new file mode 100644 index 00000000..3d4f3439 --- /dev/null +++ b/tests/test_150_questions_round_22/test_134_word_break_round_22.py @@ -0,0 +1,43 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_22\ +.ex_134_word_break import Solution + + +class WordBreakTestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + + def test_example1(self): + s = "leetcode" + wordDict = ["leet", "code"] + self.assertTrue(self.solution.wordBreak(s, wordDict)) + + def test_example2(self): + s = "applepenapple" + wordDict = ["apple", "pen"] + self.assertTrue(self.solution.wordBreak(s, wordDict)) + + def test_example3(self): + s = "catsandog" + wordDict = ["cats", "dog", "sand", "and", "cat"] + self.assertFalse(self.solution.wordBreak(s, wordDict)) + + def test_single_char_true(self): + s = "a" + wordDict = ["a"] + self.assertTrue(self.solution.wordBreak(s, wordDict)) + + def test_single_char_false(self): + s = "b" + wordDict = ["a"] + self.assertFalse(self.solution.wordBreak(s, wordDict)) + + def test_reuse_word(self): + s = "aaaaaaa" + wordDict = ["aaaa", "aaa"] + self.assertTrue(self.solution.wordBreak(s, wordDict)) + + def test_empty_string(self): + s = "" + wordDict = ["a"] + self.assertTrue(self.solution.wordBreak(s, wordDict)) \ No newline at end of file