14. Longest Common Prefix

99 阅读1分钟

题目描述

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.

解题思路

这个题目的思路就是: 先找到数组中最短的那个字符串,然后以这个字符串为准, 获取他的子串, 在循环数组中其他元素,看是否以该子串开始
时间复杂度: O(n^2)

示例代码

func longestCommonPrefix(_ strs: [String]) -> String {
    var tempStrs = Array.init(strs)
    if tempStrs.count == 0 {
        return ""
    }

    tempStrs.sort { (s1, s2) -> Bool in
        return s1.count < s2.count
    }

    guard let shortStr = tempStrs.first else {
        return ""
    }

    for index in 0...shortStr.count {
        let subStr = String(shortStr.prefix(index))
        for str in tempStrs.enumerated() {
            if !str.element.hasPrefix(subStr) {
                return String(shortStr.prefix(index-1))
            }
        }
    }
    return shortStr
}