Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit eb8f387

Browse files
committed
Add solution 140.
1 parent 08238d5 commit eb8f387

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
3+
/**
4+
* @param String $s
5+
* @param String[] $wordDict
6+
* @return String[]
7+
*/
8+
function wordBreak($s, $wordDict) {
9+
$map = [];
10+
self::wordBreakHelper($s, $wordDict, $map);
11+
return $map[$s];
12+
}
13+
14+
function wordBreakHelper($s, $dict, &$map) {
15+
if (array_key_exists($s, $map)) {
16+
return $map[$s];
17+
}
18+
19+
$list = [];
20+
21+
if ($s == "") {
22+
array_push($list, "");
23+
return $list;
24+
}
25+
26+
foreach ($dict as $currStr) {
27+
if (self::startsWith($s, $currStr)) {
28+
$tempList = self::wordBreakHelper(substr($s, strlen($currStr)), $dict, $map);
29+
if (!empty($tempList)) {
30+
foreach ($tempList as $tempStr) {
31+
array_push($list, $currStr . ($tempStr == "" ? "" : " ") . $tempStr);
32+
}
33+
}
34+
}
35+
}
36+
37+
$map[$s] = $list;
38+
return $list;
39+
}
40+
41+
function startsWith($haystack, $needle) {
42+
return strncmp($haystack, $needle, strlen($needle)) === 0;
43+
}
44+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /