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

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循环。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容