Skip to content

Commit bac32b6

Browse files
yuriymaradegonSchiele
authored andcommitted
Add PHP example for chapter 09 - dynamic programming (egonSchiele#98)
1 parent cc845c4 commit bac32b6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
/**
4+
* @param string $stringA
5+
* @param string $stringB
6+
* @return array
7+
*/
8+
function search(string $stringA, string $stringB): array
9+
{
10+
$cell = [];
11+
12+
for ($i = 0; $i < strlen($stringA); $i++) {
13+
for ($j = 0; $j < strlen($stringB); $j++) {
14+
if ($stringA[$i] === $stringB[$j]) {
15+
if (isset($cell[$i - 1][$j - 1])) {
16+
$cell[$i][$j] = $cell[$i - 1][$j - 1] + 1;
17+
} else {
18+
$cell[$i][$j] = 1;
19+
}
20+
} else {
21+
if (isset($cell[$i - 1][$j]) || isset($cell[$i][$j - 1])) {
22+
$cell[$i][$j] = max(
23+
isset($cell[$i - 1][$j]) ? $cell[$i - 1][$j] : 0,
24+
isset($cell[$i][$j - 1]) ? $cell[$i][$j - 1] : 0
25+
);
26+
} else {
27+
$cell[$i][$j] = 0;
28+
}
29+
}
30+
}
31+
}
32+
33+
return $cell;
34+
}
35+
36+
print_r(search('fish', 'fosh'));
37+
38+
/*
39+
[ f o s h
40+
f [1,1,1,1],
41+
i [1,1,1,1],
42+
s [1,1,2,2],
43+
h [1,1,2,3]
44+
]
45+
*/

0 commit comments

Comments
 (0)