自己的思路:
纵向比较
从第0位开始依次比较各个字符串的字符,记录公共子前缀,如果出现数组越界直接返回当前的公共子前缀
代码:
fun longestCommonPrefix(strs: Array<String>): String {
var result = StringBuilder()
if (strs.size == 1) {
return strs[0]
}
for (charIndex in 0 until strs[0].length) {
var quit = false
for (strIndex in 1 until strs.size) {
if (charIndex >= strs[strIndex].length || strs[0][charIndex] != strs[strIndex][charIndex]) {
quit = true
}
}
if (quit) {
return result.toString()
} else {
result.append(strs[0][charIndex])
}
}
return result.toString()
}