題目
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:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
翻譯
這題題目很容易理解,找出所有字串的前綴字元,把全部相同的部分抓出來,也就是說,[“flower”,“flow”,“flight”] 全部相同的部分就是 fl,如果都沒有前綴字元,則回傳空字串。
思維
這題題目先把所有字串看成一維陣列。
[
[f, l, o, w, e, r],
[f, l, o, w],
[f, l, i, g, h, t]
]
接著對這個二維陣列排序。
[
[f, l, o, w],
[f, l, o, w, e, r],
[f, l, i, g, h, t]
]
基本上最短的字串進行比對,如果連最短的字串都不符合,代表全部都不符合了,因為條件就是公共的字串要一致,所以先排序會是一個比較好的做法。
實作
透過 firstOrNull 可以找到第一個符合的字元。
fun longestCommonPrefix(strs: Array<String>): String {
if (strs.isEmpty()) {
return ""
}
if (strs.size == 1) {
return strs[0]
}
strs.sort()
return strs[0].indices
.firstOrNull { strs[0][it] != strs[strs.size - 1][it] }
?.let { strs[0].substring(0, it) }
?: strs[0]
}