算法-Longest Common Prefix【swift4实现】

原题连接:https://leetcode.com/problems/longest-common-prefix/description/

算法-Longest Common Prefix【swift4实现】_第1张图片

解决:

func longestCommonPrefix(_ strs: [String]) -> String {
        if strs.count == 0 {
            return ""
        } else if strs.count == 1 {
            return strs[0]
        }
        
        let firtStr = strs[0]
        var result = ""
        for cha in firtStr {
            result = result + String(cha)
            var count: Int? = 0
            for str in strs {
                if str == "" {
                    result = ""
                    break
                }
                if str.hasPrefix(result) && result != "" {
                    count = count! + 1
                }
            }
            if count == strs.count {
                continue
            } else {
                if result.count > 0 {
                    result = String(result.prefix(result.count - 1))
                }
                break;
            }
        }
        return result
    }

你可能感兴趣的:(算法)