LeetCode14.最长公共前缀(Kotlin语言)
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"] 输出: "fl" 示例 2:
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明:
所有输入只包含小写字母 a-z 。
解题思路
1.先计算出数组中的最短字符串长度 shortestStrLen 2.最长公共前缀 <= shortestStrLen 3.for len in 0..shortestStrLen 逐一遍历 strs 中的元素,比对是否相等 4.遇到不相等的 len, 就停止遍历,记录此时的 maxCommonLen = len. 5.注意考虑遍历完 shortestStrLen,都相等的情况, 此时 maxCommonLen = shortestStrLen
代码
代码语言:javascript复制class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
if (strs.isEmpty()) return ""
// 数组中的最短的字符串长度
var shortestStrLen = Int.MAX_VALUE
strs.forEach {
shortestStrLen = Math.min(it.length, shortestStrLen)
}
if (shortestStrLen == 0) return ""
val n = strs.size
var maxCommonLen = 0
var flag = true
for (len in 0 until shortestStrLen) {
for (i in 1 until n) {
if (strs[i][len] != strs[0][len]) {
flag = false
break
}
}
// 遍历中断
if (!flag) {
maxCommonLen = len
break
} else {
// 全部遍历均相同
maxCommonLen = shortestStrLen
}
}
return strs[0].subSequence(0, maxCommonLen).toString()
}
}
运行测试
代码语言:javascript复制fun main() {
run {
val strs = arrayOf("flower", "flow", "flight")
val common = longestCommonPrefix(strs)
println("common=$common, expected=fl")
}
run {
val strs = arrayOf("dog", "racecar", "car")
val common = longestCommonPrefix(strs)
println("common=$common, expected=")
}
run {
val strs = arrayOf("doger", "dogeracecar", "dogercar")
val common = longestCommonPrefix(strs)
println("common=$common, expected=doger")
}
run {
val strs = arrayOf("abca", "aba", "aaab")
val common = longestCommonPrefix(strs)
println("common=$common, expected=a")
}
run {
val strs = arrayOf("c", "acc", "ccc")
val common = longestCommonPrefix(strs)
println("common=$common, expected=")
}
run {
val strs = arrayOf("aac", "acab", "aa", "abba", "aa")
val common = longestCommonPrefix(strs)
println("common=$common, expected=a")
}
}
// 输出:
common=fl, expected=fl
common=, expected=
common=doger, expected=doger
common=a, expected=a
common=, expected=
common=a, expected=a
参考资料
https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-kotlinyu-yan-by-chen/