Swift刷LeetCode 之 14-Longest Common Prefix-Easy

17 篇文章 0 订阅
14 篇文章 0 订阅

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.

Idea:

Loop through each words in the array of strings. When i equals to 0, which is first string in the array, keep record of first X letter as a char, and compare the char to other strings. If other strings don't have the char at the X place, which means they don't have common prefix, return result. Each time when the internal for-loop is completed, adding the char to the result and increasing 1 to the stringIndex.

循环遍历字符串数组中的每个单词。当i = 0时,也就是数组中的第一个字符串,记录第X个字母作为char,并将char与其他字符串进行比较。如果其他strings在X位置没有char,这意味着它们没有相同前缀,则返回结果。每次当内部for循环完成时,将char添加到结果中,并在stringIndex中增加1。

        func longestCommonPrefix(_ strs: [String]) -> String {
            if strs.count == 0 {return ""}
            var res = ""
            var stringIndex = 0
            var char :Character?
            while true{
                for i in 0..<strs.count{
                    if stringIndex >= strs[i].count {return res}
                    if i==0 {char = strs[i].dropFirst(stringIndex).first}
                    else{
                        if char != strs[i].dropFirst(stringIndex).first{
                            return res
                        }
                    }
                }
                if char != nil { res.append(char!)}
                stringIndex += 1
            }
            
            return res
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值