• 作者: 负雪明烛
  • 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. 自定义char类型字符,django中事务

    自定义char类型字符 # 自定义char类型,继承Field父类 class MyCharField(Field): def __init__(self, max_length, *args, ** ...

  2. Demo04分解质因数

    package 习题集1;import java.util.Scanner;//将一个正整数分解质因数.例如输入90,打印出90=2*3*3*5public class Demo04 { public ...

  3. 到底什么是自动化优先思维?与RPA有什么关系?

    基于RPA的自动化优先,正在成为广大组织的主流管理思维 到底什么是自动化优先思维?与RPA有什么关系? 如何用RPA简单快速的打造一个自动化优先的组织? 文/王吉伟 在IT运维项目中,组织经常会遇到先 ...

  4. Windows端口被占用解决方法

    Error 场景 启动 Java 项目失败,控制台显示 Error starting ApplicationContext. To display the conditions report`re-r ...

  5. Qt最好用评价最高的是哪个版本?

    来源: http://www.qtcn.org/bbs/read-htm-tid-89455.html /// Qt4:    4.8.7      4.X 系列终结版本 Qt5 :   5.6 LT ...

  6. eclipse上安装 windowBuilder方法

    最近因为需要用java Swing做一些组件设计,但想想以前在大学时候为了布局组件和位置设计花了很多时间.所以再网上查了一些带有可视化的设计插件用来提高工作效率. 其中一个是 windowBuilde ...

  7. MyBatis常用批量方法

    <!-- 批量添加派车单子表数据 --> <insert id="addBatch" parameterType="java.util.List&quo ...

  8. Java Bean 与Spring Bean 的区别

    什么是JavaBean: JavaBean是一种JAVA语言写的可重用组件.JavaBean符合一定规范写的Java类,是一种规范.它的方法命名,构造以及行为必须符合特定的要求:     1.所有属性 ...

  9. 【力扣】337. 打家劫舍 III

    在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区.这个地区只有一个入口,我们称之为"根". 除了"根"之外,每栋房子有且只有一个" ...

  10. [WPF] 用 OpacityMask 模仿 UWP 的 Text Shimmer 动画

    1. UWP 的 Text Shimmer 动画 在 UWP 的 Windows Composition Samples 中有一个 Text Shimmer 动画,它用于展示如何使用 Composit ...