funclongestCommonPrefix(_strs: [String]) -> String { funcprefixOfInsertion(_str1: String, _str2: String) -> String { let length =min(str1.count, str2.count) var index =0 while index < length && str1.prefix(index +1) == str2.prefix(index +1) { index +=1 } returnString(str1.prefix(index)) } var res = strs[0] for index in1..< strs.count { res = prefixOfInsertion(res, strs[index]) } return res }
解法2:纵向比较
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funclongestCommonPrefix2(_strs: [String]) -> String { let count = strs[0].count for i in0..< count { letprefix= strs[0].prefix(i +1) for str in strs { if str.prefix(i +1) !=prefix { returnString(str.prefix(i)) } } } return strs[0] }