前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-14. Longest Common Prefix | 最长公共前缀

LeetCode-14. Longest Common Prefix | 最长公共前缀

作者头像
Zoctopus
发布2021-02-25 17:14:41
3740
发布2021-02-25 17:14:41
举报

题目

LeetCode LeetCode-cn

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 "".

代码语言:javascript
复制
Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
 

Constraints:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

题解

这道题目的简单描述就是找一堆字符串的相同前缀,比如flowerflowflight,发现每个字符串都有前缀fl,于是就将fl返回即可,本题就是要实现这样一个在字符串数组中找最长前缀的函数。

解法一:暴力

代码语言:javascript
复制
//Go
func longestCommonPrefix(strs []string) string {
	//排除特殊情况
	if len(strs) == 0 {
		return ""
	}
	if len(strs) == 1 {
		return strs[0]
	}
	res := strs[0]               //获取字符串数组里的第一个元素
	for _, v := range strs[1:] { //从字符串数组第二个元素开始遍历
		var i int
		for ; i < len(v) && i < len(res); i++ { //遍历两数组里的元素
			if res[i] != v[i] { //做判断,如果不相等
				break //直接结束循环
			}
		}
		res = res[:i]
		if res == "" {
			return res //返回空
		}
	}

	return res
}

另一种相似解法,会用到strings.Index

代码语言:javascript
复制
//Go
func longestCommonPrefix(strs []string) string {
    if len(strs) < 1 {
        return ""
    }
    prefix := strs[0]
    for _,k := range strs {
        for strings.Index(k,prefix) != 0 {
            if len(prefix) == 0 {
                return ""
            }
            prefix = prefix[:len(prefix) - 1]
        }
    }
    return prefix
}

执行结果:

代码语言:javascript
复制
力扣:
执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2.3 MB, 在所有 Go 提交中击败了55.76%的用户

leetcode:
Runtime: 0 ms, faster than 100.00% of Go online submissions for Longest Common Prefix.
Memory Usage: 2.4 MB, less than 100.00% of Go online submissions for Longest Common Prefix.

参考题解

力扣官方题解-5种解法

github博客地址

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-02-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
    • 解法一:暴力
    • 参考题解
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档