URL: https://leetcode.com/problems/longest-common-prefix/ Signed-off-by: Matej Focko <me@mfocko.xyz>
18 lines
525 B
Kotlin
18 lines
525 B
Kotlin
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)
|
|
}
|
|
}
|