kt: add «14. Longest Common Prefix»
URL: https://leetcode.com/problems/longest-common-prefix/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
989f2b071e
commit
fb06fb1fc6
1 changed files with 18 additions and 0 deletions
18
kt/longest-common-prefix.kt
Normal file
18
kt/longest-common-prefix.kt
Normal file
|
@ -0,0 +1,18 @@
|
|||
class Solution {
|
||||
private fun findCommonPrefix(
|
||||
x: String,
|
||||
y: String,
|
||||
): String =
|
||||
minOf(x.length, y.length).let { maxLength ->
|
||||
(0..maxLength - 1).takeWhile { i ->
|
||||
x[i] == y[i]
|
||||
}.lastOrNull() ?: -1
|
||||
}.let { maxIndex ->
|
||||
x.substring(0, maxIndex + 1)
|
||||
}
|
||||
|
||||
fun longestCommonPrefix(strs: Array<String>): String =
|
||||
strs.drop(1).fold(strs[0]) { commonPrefix, str ->
|
||||
findCommonPrefix(commonPrefix, str)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue