File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
09_dynamic_programming/php Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments