zoukankan      html  css  js  c++  java
  • LeetCode最长公共前缀Swift

    编写一个函数来查找字符串数组中的最长公共前缀。

    如果不存在公共前缀,返回空字符串 ""。

    示例 1:

    输入: ["flower","flow","flight"]
    输出: "fl"


    示例 2:

    输入: ["dog","racecar","car"]
    输出: ""
    解释: 输入不存在公共前缀。


    说明:

    所有输入只包含小写字母 a-z 。

    思路:

    以第一个字符串为最大公共前缀,从第二个字符串开始判断是否存在该前缀,不存在时将字符串从后开始缩减直到存在,然后挨个遍历字符串数组。 

    class Solution {
        func longestCommonPrefix(_ strs: [String]) -> String {
            guard strs.count > 0 else {return ""}
            var result = strs[0]
            for (i,str) in strs.enumerated() {
                if i==0 {continue}
                while !str.hasPrefix(result) {
                    result.removeLast()
                }
            }
            return result
        }
    }
  • 相关阅读:
    pat00-自测5. Shuffling Machine (20)
    Spiral Matrix
    Search in Rotated Sorted Array II
    Search in Rotated Sorted Array
    Best Time to Buy and Sell Stock II
    4Sum
    3Sum Closest
    3Sum
    MySQL存储过程、函数和游标
    Word Ladder
  • 原文地址:https://www.cnblogs.com/huangzs/p/13729639.html
Copyright © 2011-2022 走看看