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

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!