140. Word Break II #105
-
Given a string Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
To solve this problem, we can follow these steps:
Key Components
Let's implement this solution in PHP: 140. Word Break II <?php
function wordBreak($s, $wordDict) {
if(array_key_exists($s, $this->map)) {
return $this->map[$s];
}
$result = array();
if(strlen($s) == 0){
$result[] = "";
$this->map[""] = $result;
return $result;
}
foreach($wordDict as $word) {
if(strpos($s, $word) === 0){
$subWords = wordBreak(substr($s, strlen($word)), $wordDict);
foreach($subWords as $subWord) {
$result[] = $word . (strlen($subWord) > 0 ? " " : "") . $subWord;
}
}
}
$this->map[$s] = $result;
return $result;
}
// Example usage:
$s = "catsanddog";
$wordDict = array("cat","cats","and","sand","dog");
print_r(wordBreak($s, $wordDict)); // Output: ["cats and dog","cat sand dog"]
$s = "pineapplepenapple";
$wordDict = array("apple","pen","applepen","pine","pineapple");
print_r(wordBreak($s, $wordDict)); // Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
$s = "catsandog";
$wordDict = array("cats","dog","sand","and","cat");
print_r(wordBreak($s, $wordDict)); // Output: []
?> Explanation:
This approach is effective but may not be the most efficient for large inputs due to its exponential nature. The memoization helps mitigate redundant computations, but the overall complexity can still be high. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
s
using the words inwordDict
, where each word can be used multiple times.Key Components
Memoization Check (
$this->map
):$this->map
to store previously computed results for substrings. This prevents redundant computations and improves efficiency.s
is already present in$this->map
, the function returns the cached result for that substring.Base Case:
s
is 0 (i.e., an empty string), it means we have successfully segmented the string up to this point, so we add an empty string to the resul…