Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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]
Original file line number Diff line number Diff line change
@@ -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];
}
43 changes: 43 additions & 0 deletions tests/test_150_questions_round_22/test_134_word_break_round_22.py
Original file line number Diff line number Diff line change
@@ -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))
Loading