美文网首页工作生活
5.最长公共前缀-Longest Common Prefix

5.最长公共前缀-Longest Common Prefix

作者: 快乐捣蛋鬼 | 来源:发表于2019-07-16 18:39 被阅读0次

LeetCode Link: https://leetcode.com/problems/longest-common-prefix/

Description:

Write a function to find the longest common prefix string amongst an array of strings.
写一个函数找到一个String类型的数组中的最长公共前缀。
If there is no common prefix, return an empty string "".
如果没有公共前缀,返回空字符串。
All given inputs are in lowercase letters a-z.
所有输入只包含小写字母 a-z 。

Example:

Input: ["flower","flow","flight"]
Output: "fl"

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Tints:

1.找到长度最短的字符串,并将其看作最长公共前缀commonPrefix。
2.在数组中遍历,检查是否每个元素都包括commonPrefix,如果没有,commonPrefix去掉最后一个字母,继续循环

Solution:

import Foundation

func longestCommonPrefix(_ strs: [String]) -> String {
    var shortest: String?   // 长度最短的字符串
    var length = Int.max    // 最短字符串的长度
    
    for str in strs {
        if str.count < length {
            length = str.count
            shortest = str
        }
    }
    
    if var commonPrefix = shortest {
        var endIndex = commonPrefix.endIndex
        for str in strs {
            while !commonPrefix.isEmpty && !str.hasPrefix(commonPrefix) {
                endIndex = commonPrefix.index(before: endIndex) // endIndex 减 1
                commonPrefix = String(commonPrefix.prefix(upTo: endIndex))  // 公共前缀减去最后一个字母
            }
        }
        return commonPrefix
    } else {
        return ""
    }
}

Runtime: 16 ms, faster than 94.16% of Swift online submissions for Longest Common Prefix.

Memory Usage: 20.3 MB, less than 5.61% of Swift online submissions for Longest Common Prefix.

Analyze:直接使用长度最短的字符串作为最长公共前缀的初始值,可以少几次while循环。

相关文章

网友评论

    本文标题:5.最长公共前缀-Longest Common Prefix

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