题解 | #最长公共前缀#

最长公共前缀

https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47

class Solution:
    def longestCommonPrefix(self , strs: List[str]) -> str:
        target = ""
        minL = 5001
        # 找到最短的字符串
        for i in strs:
            if len(i) < minL:
                minL = len(i)
                target = i
       
        while target:
            count = 0
            for i in range(len(strs)):
                if target not in strs[i]:
                    break
                else:
                    count += 1
            
            if count == len(strs):
                break

            target = target[:len(target)-1]
            
        return target

解题思路

  • 先遍历字符串数组,得到最短的字符串,作为目标字符串;
  • 遍历字符串数组,判断目标字符串是否在所有的字符串中,如果不是,则将目标字符串的最后一位去掉,进行下一轮的比较;如果是,则返回当前目标字符串。

复杂度

  • 时间复杂度为(n*len);
  • 空间复杂度为O(1)。
全部评论

相关推荐

09-28 22:01
已编辑
广西科技大学 IT技术支持
合适才能收到offe...:找桌面运维?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务