• 作者: 负雪明烛
  • id: fuxuemingzhu
  • 个人博客:http://fuxuemingzhu.cn/
  • 个人公众号:负雪明烛
  • 本文关键词:prefix, 公共前缀,题解,leetcode, 力扣,Python, C++, Java

题目地址:https://leetcode.com/problems/longest-common-prefix/description/

题目描述

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.

题目大意

找所有字符串的最长公共前缀。

解题方法

遍历前缀子串

遍历数组的第一个字符串的所有可能前缀字符串,看其他字符串的前缀是否全部一样。

用到的一个技巧是使用了all函数,判断所有的是否都满足条件。而是注意字符串切片,因为xrange是从0开始数的,而字符串切片的第二个数字是结束位置(不包含),这样必须让切片的位置加一才行。就是代码第13行。

class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if strs == None or len(strs) == 0:
return ""
def is_common(prefix, strs):
return all(str.startswith(prefix) for str in strs)
answer = ''
for i in xrange(len(strs[0])):
pre = strs[0][:i + 1]
print pre
if is_common(pre, strs):
answer = pre
else:
break
return answer

使用set

用set能获得去重的前缀有多少,如果只有一个的话,说明大家的前缀是相等的。

class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
pre = ""
_len = min(len(s) for s in strs)
for i in range(1, _len + 1):
if len(set(s[:i] for s in strs)) == 1:
pre = strs[0][:i]
return pre

遍历最短字符串

又学到了一个新的找最短字符串的方法,就是min函数可以用key=len。

然后我们遍历这个最短字符串的每一位,如果所有的字符串中有个字符串的前缀不是这个字符的话,那么就返回当前的切片。如果遍历结束仍然没有提前返回的话,就返回这个最短的子串。

class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
pre = min(strs, key = len)
for i, c in enumerate(pre):
for word in strs:
if word[i] != c:
return pre[:i]
return pre

C++版本如下:

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) return "";
string pre = strs[0];
for (auto word : strs){
if (word.size() < pre.size()){
pre = word;
}
}
for (int i = 0; i < pre.size(); ++i){
for (auto word : strs){
if (word.at(i) != pre.at(i)){
return pre.substr(0, i);
}
}
}
return pre;
}
};

排序

因为我们排序之后,相同的前缀字符串会尽量在一起,所以,我们只要判断第一个字符串和最后一个字符串的最长公共前缀就好了。

class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
strs.sort()
size = min(len(strs[0]), len(strs[-1]))
i = 0
while i < size and strs[0][i] == strs[-1][i]:
i += 1
return strs[0][:i]

C++代码如下:

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
sort(strs.begin(), strs.end());
int size = min(strs[0].size(), strs.back().size());
int i = 0;
while (i < size && strs[0].at(i) == strs.back().at(i)){
++i;
}
return strs[0].substr(0, i);
}
};

日期

2017 年 8 月 25 日
2018 年 11 月 24 日 —— 周日开始!一周就过去了~

【LeetCode】14. Longest Common Prefix 最长公共前缀的更多相关文章

  1. [LeetCode]14. Longest Common Prefix最长公共前缀

    Write a function to find the longest common prefix string amongst an array of strings. If there is n ...

  2. [leetcode]14. Longest Common Prefix 最长公共前缀

    Write a function to find the longest common prefix string amongst an array of strings. If there is n ...

  3. Leetcode No.14 Longest Common Prefix最长公共前缀(c++实现)

    1. 题目 1.1 英文题目 Write a function to find the longest common prefix string amongst an array of strings ...

  4. [LeetCode] 14. Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. If there is n ...

  5. 【LeetCode】Longest Common Prefix(最长公共前缀)

    这道题是LeetCode里的第14道题. 题目描述: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["f ...

  6. # Leetcode 14:Longest Common Prefix 最长公共前缀

    公众号:爱写bug Write a function to find the longest common prefix string amongst an array of strings. If ...

  7. LeetCode Longest Common Prefix 最长公共前缀

    题意:给多个字符串,返回这些字符串的最长公共前缀. 思路:直接逐个统计同一个位置上的字符有多少种,如果只有1种,那么就是该位是相同的,进入下一位比较.否则终止比较,返回前缀.可能有一个字符串会比较短, ...

  8. Longest Common Prefix -最长公共前缀

    问题:链接 Write a function to find the longest common prefix string amongst an array of strings. 解答: 注意 ...

  9. Leetcode 14. Longest Common Prefix(水)

    14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...

随机推荐

  1. 22-reverseString-Leetcode

    思路:so easy class Solution { public: string reverseString(string s) { int n = s.size(); for(int i=0;i ...

  2. SpringBoot整合Shiro 三:整合Mybatis

    搭建环境见: SpringBoot整合Shiro 一:搭建环境 shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类 整合Mybatis 添加Maven依赖 mysql.dr ...

  3. matplotlib以对象方式绘制子图

    matplotlib有两种绘图方式,一种是基于脚本的方式,另一种是面向对象的方式 面向脚本的方式类似于matlab,面向对象的方式使用起来更为简便 创建子图的方式也很简单 fig,ax = plt.s ...

  4. 数据库之JDBC

    1.简单认识一下JDBC 1).JDBC是什么? java database connection       java数据库连接 作用:就是为了java连接mysql数据库嘛 要详细的,就面向百度编 ...

  5. android获取路径目录方法

    Environment常用方法: getExternalStrongeDirectory() 返回File,获取外部存储目录即SDCard getDownloadCacheDirectory() 返回 ...

  6. lucene索引的增、删、改

    package com.hope.lucene;import org.apache.lucene.document.Document;import org.apache.lucene.document ...

  7. ActiveMQ(三)——理解和掌握JMS(1)

    一.JMS基本概念 JMS是什么JMS Java Message Service,Java消息服务,是JavaEE中的一个技术. JMS规范JMS定义了Java中访问消息中间件的接囗,并没有给予实现, ...

  8. 一行配置搞定 Spring Boot项目的 log4j2 核弹漏洞!

    相信昨天,很多小伙伴都因为Log4j2的史诗级漏洞忙翻了吧? 看到群里还有小伙伴说公司里还特别建了800+人的群在处理... 好在很快就有了缓解措施和解决方案.同时,log4j2官方也是速度影响发布了 ...

  9. 1、Redis简介

    一.NOSQL 1.什么是NOSQL? NoSQL(NoSQL = Not Only SQL ),意即"不仅仅是SQL". 指的是非关系型的数据库.NoSQL有时也称作Not On ...

  10. MVCC详解

    参考: https://blog.csdn.net/SnailMann/article/details/94724197 https://blog.csdn.net/DILIGENT203/artic ...