美文网首页
14. 最长公共前缀 LeetCode

14. 最长公共前缀 LeetCode

作者: 出来遛狗了 | 来源:发表于2018-11-02 10:56 被阅读3次
image.png
class Solution {
    func longestCommonPrefix(_ strs: [String]) -> String {
        if strs.count < 1 {
            return "";
        }else{
            var result = strs.first;
            for i in 1..<strs.count{
                var count = 0;
                if (result?.count)! < strs[i].count{
                    count = (result?.count)!
                }else{
                    count = strs[i].count
                }
                if count == 0{
                    return ""
                }
                for j in 0..<count{
                    let c = result?.charAt(index: j);
                    let c2 = strs[i].charAt(index: j);
                    if c == c2{
                        if j == count - 1{
                            result = String((result?.prefix(j + 1))!);
                        }
                    }else{
                        result = String((result?.prefix(j))!);
                    }
                    if result?.count == 0 {
                        return result!;
                    }
                }
            }
            return result!;
        }
    }
}
extension String{
    func charAt(index:Int)->Character?{
        if index >= self.count || index < 0{
            return nil
        }
        let i = self.index(self.startIndex, offsetBy:index)
        return self[i]
    }
}

相关文章

  • 14. 最长公共前缀

    14. 最长公共前缀[https://leetcode-cn.com/problems/longest-commo...

  • LeetCode学习计划:LeetCode 75-Level-2

    14. 最长公共前缀[https://leetcode.cn/problems/longest-common-pr...

  • 算法第3天:最长公共前缀

    leetcode 14. 最长公共前缀 simple 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共...

  • 2.算法-分治

    二分模板 经典例题 14. 最长公共前缀[https://leetcode-cn.com/problems/lon...

  • 14. 最长公共前缀

    20180923-摘抄自14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,...

  • [day4] [LeetCode] [title14,122]

    14.最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例 ...

  • 14. 最长公共前缀

    14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 说明...

  • 14.最长公共前缀

    14.最长公共前缀 难度:简单 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ...

  • LeetCode 每日一题 [19] 最长公共前缀

    LeetCode 最长公共前缀 [简单] 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回...

  • 14. 最长公共前缀

    14.最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例1...

网友评论

      本文标题:14. 最长公共前缀 LeetCode

      本文链接:https://www.haomeiwen.com/subject/jnpqxqtx.html