LeetCode #14 Longest Common Prefix
LeetCode #14 Longest Common Prefix
Question
Write a function to find the longest common prefix string amongst an array of strings.
Solution
Approach #1
class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
if strs.isEmpty { return "" }
let utf16s = strs.map { Array($0.utf16) }
for i in 0..<utf16s[0].count {
for j in 1..<utf16s.count {
if i == utf16s[j].count || utf16s[0][i] != utf16s[j][i] {
return String(utf16CodeUnits: Array(utf16s[0][0..<i]), count: i)
}
}
}
return strs[0]
}
}
Time complexity: O(m * n). m is the length of strs, and n is the length of first string in strs.
Space complexity: O(m * n). We need to create array of utf16 array (utf16s).
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7065443.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步