美文网首页
[LeetCode]14、最长前缀

[LeetCode]14、最长前缀

作者: 河海中最菜 | 来源:发表于2019-07-27 14:45 被阅读0次

题目描述

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

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

示例 1:

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

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

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

思路

  • 思路1
    1、第一层遍历第一个字符串所有字符
    2、第二层遍历剩下的每个字符串的对应位置
    匹配不相等,则退出,返回长度
  • 思路2
    遍历剩下所有字符串除第一个
    利用该字符串查找到第一个字符串为止,否则进行缩短
    遍历完所有字符串返回
class Solution:
    # def longestCommonPrefix(self, strs: List[str]) -> str:
    #     if not strs or len(strs) == 0:
    #         return ""
    #     res = ""
    #     for j in range(len(strs[0])):
    #         for i in range(len(strs)):
    #             if (j < len(strs[i]) and strs[i][j] != strs[0][j]) or j == len(strs[i]):
    #                 return res
    #         res += strs[0][j]
    #     return res
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs or len(strs) == 0:
            return ""
        res = strs[0]
        for i in range(1, len(strs)):
            while strs[i].find(res) != 0:
                res = res[:len(res)-1]
        return res
AC14

相关文章

  • 14. 最长公共前缀

    14. 最长公共前缀[https://leetcode-cn.com/problems/longest-commo...

  • LeetCode学习计划:LeetCode 75-Level-2

    14. 最长公共前缀[https://leetcode.cn/problems/longest-common-pr...

  • [LeetCode]14、最长前缀

    题目描述 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输...

  • LeetCode14.最长公共前缀 JavaScript

    LeetCode14.最长公共前缀 JavaScript 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在...

  • 算法第3天:最长公共前缀

    leetcode 14. 最长公共前缀 simple 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共...

  • 2.算法-分治

    二分模板 经典例题 14. 最长公共前缀[https://leetcode-cn.com/problems/lon...

  • 14最长公共前缀

    2019年04月24日 Day05 级别:简单 LeetCode 14 题目: 最长公共前缀 编写一个函数来...

  • Leetcode 14 最长公共前缀

    编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 " "。示例 1:输入: ["fl...

  • LeetCode 14最长公共前缀

    题目: 思路: 方法一:拿出数组的首元素,把首元素的各个字母元素与strs数组的第二项、第三项等等的各个字母相比较...

  • Leetcode 14 最长公共前缀

    最长公共前缀 题目 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

网友评论

      本文标题:[LeetCode]14、最长前缀

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