|
| 1 | +export class WordBreakSolution { |
| 2 | + // Function to determine if the input string 's' can be segmented into words from the 'wordDict' |
| 3 | + wordBreak(s, wordDict) { |
| 4 | + const wordSet = new Set(wordDict) // Convert wordDict into a set for efficient lookups |
| 5 | + const memo = Array(s.length).fill(null) // Initialize memoization array to store results of subproblems |
| 6 | + return this.canBreak(0, s, wordSet, memo) // Start the recursive function from the 0th index |
| 7 | + } |
| 8 | + |
| 9 | + // Helper function to perform recursive backtracking with memoization |
| 10 | + canBreak(start, s, wordSet, memo) { |
| 11 | + if (start === s.length) { |
| 12 | + return true // If we reach the end of the string, return true as we successfully segmented it |
| 13 | + } |
| 14 | + |
| 15 | + if (memo[start] !== null) { |
| 16 | + return memo[start] // Return the cached result if already computed for this index |
| 17 | + } |
| 18 | + |
| 19 | + // Explore all possible substrings starting from 'start' index |
| 20 | + for (let end = start + 1; end <= s.length; end++) { |
| 21 | + const currentSubstring = s.slice(start, end) // Get the substring from 'start' to 'end' |
| 22 | + |
| 23 | + // If the current substring is a valid word and the rest of the string can be broken, return true |
| 24 | + if ( |
| 25 | + wordSet.has(currentSubstring) && |
| 26 | + this.canBreak(end, s, wordSet, memo) |
| 27 | + ) { |
| 28 | + memo[start] = true // Cache the result as true for this index |
| 29 | + return true |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + memo[start] = false // Cache the result as false if no valid segmentation found |
| 34 | + return false |
| 35 | + } |
| 36 | +} |
0 commit comments