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
.
Idea:
Loop through each words in the array of strings. When i equals to 0, which is first string in the array, keep record of first X letter as a char, and compare the char to other strings. If other strings don't have the char at the X place, which means they don't have common prefix, return result. Each time when the internal for-loop is completed, adding the char to the result and increasing 1 to the stringIndex.
循环遍历字符串数组中的每个单词。当i = 0时,也就是数组中的第一个字符串,记录第X个字母作为char,并将char与其他字符串进行比较。如果其他strings在X位置没有char,这意味着它们没有相同前缀,则返回结果。每次当内部for循环完成时,将char添加到结果中,并在stringIndex中增加1。
func longestCommonPrefix(_ strs: [String]) -> String {
if strs.count == 0 {return ""}
var res = ""
var stringIndex = 0
var char :Character?
while true{
for i in 0..<strs.count{
if stringIndex >= strs[i].count {return res}
if i==0 {char = strs[i].dropFirst(stringIndex).first}
else{
if char != strs[i].dropFirst(stringIndex).first{
return res
}
}
}
if char != nil { res.append(char!)}
stringIndex += 1
}
return res
}