File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
main/kotlin/hackerrank/string
test/kotlin/hackerrank/string Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ package hackerrank.string
2
+
3
+ import kotlin.math.max
4
+
5
+ /* *
6
+ * AA, BB
7
+ * HARRY, SALLY
8
+ * SHINCHAN, NOHARAAA
9
+ * ABCDEF, FBDAMN
10
+ *
11
+ * SHINCHAHN
12
+ * N 000111111
13
+ * O -
14
+ * H 011111111
15
+ * H 011112222
16
+ * A 011112333
17
+ * R -
18
+ * A -
19
+ * A -
20
+ * A -
21
+ *
22
+ */
23
+ fun commonChild (s1 : String , s2 : String ): Int {
24
+ val counts = Array (s1.length + 1 ) { IntArray (s2.length + 1 ) }
25
+
26
+ s1.forEachIndexed { i1, c1 ->
27
+ s2.forEachIndexed { i2, c2 ->
28
+ counts[i1 + 1 ][i2 + 1 ] = if (c1 == c2) {
29
+ counts[i1][i2] + 1
30
+ } else {
31
+ max(counts[i1 + 1 ][i2], counts[i1][i2 + 1 ])
32
+ }
33
+ }
34
+
35
+ printMatrix(counts, s1, s2)
36
+ }
37
+
38
+ return counts[s1.length][s2.length]
39
+ }
40
+
41
+ private fun printMatrix (counts : Array <IntArray >, s1 : String , s2 : String ) {
42
+ val s2Joined = s2.toCharArray().joinToString(" " )
43
+
44
+ var s1CharIndex = 0
45
+ val joined = counts
46
+ .filterIndexed { i, _ -> i > 0 }
47
+ .joinToString(" \n " ) {
48
+ " ${s1[s1CharIndex++ ]} ${it.filterIndexed { i, _ -> i > 0 }.joinToString(" " )} "
49
+ }
50
+
51
+ println (" matrix is...\n $s2Joined \n $joined " )
52
+ }
Original file line number Diff line number Diff line change
1
+ package hackerrank.string
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+
6
+ class CommonChildKtTest {
7
+
8
+ @Test
9
+ fun commonChild () {
10
+ assertEquals(0 , commonChild(" AA" , " BB" ))
11
+ assertEquals(2 , commonChild(" HARRY" , " SALLY" ))
12
+ assertEquals(3 , commonChild(" SHINCHAN" , " NOHARAAA" ))
13
+ assertEquals(2 , commonChild(" ABCDEF" , " FBDAMN" ))
14
+ }
15
+
16
+ }
You can’t perform that action at this time.
0 commit comments