14. Longest Common Prefix

  • Source : Link
  • Author : Han
  • Date : 2022-01-24

Problems

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty stringĀ "".

Example 1:

1
2
3
Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

1
2
3
4
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    fun longestCommonPrefix(strs: Array<String>): String {
        var result = ""
        var index = 0
        strs.sortBy { it.length }
        val first = strs.first()
        while(index < first.length) {
            var isPass = true
            val temp = first[index]
            strs.forEachIndexed run@{ _, str ->
                isPass = isPass && str[index] == temp
                when {
                    !isPass -> return@run
                }
            }
            when {
                isPass -> result += temp
                else -> return result
            }
            index++
        }
        return result
    }
}