【LeetCode】14. Longest Common Prefix 最长公共前缀
- 作者: 负雪明烛
- 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 最长公共前缀的更多相关文章
- [LeetCode]14. Longest Common Prefix最长公共前缀
Write a function to find the longest common prefix string amongst an array of strings. If there is n ...
- [leetcode]14. Longest Common Prefix 最长公共前缀
Write a function to find the longest common prefix string amongst an array of strings. If there is n ...
- 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 ...
- [LeetCode] 14. Longest Common Prefix 最长共同前缀
Write a function to find the longest common prefix string amongst an array of strings. If there is n ...
- 【LeetCode】Longest Common Prefix(最长公共前缀)
这道题是LeetCode里的第14道题. 题目描述: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["f ...
- # Leetcode 14:Longest Common Prefix 最长公共前缀
公众号:爱写bug Write a function to find the longest common prefix string amongst an array of strings. If ...
- LeetCode Longest Common Prefix 最长公共前缀
题意:给多个字符串,返回这些字符串的最长公共前缀. 思路:直接逐个统计同一个位置上的字符有多少种,如果只有1种,那么就是该位是相同的,进入下一位比较.否则终止比较,返回前缀.可能有一个字符串会比较短, ...
- Longest Common Prefix -最长公共前缀
问题:链接 Write a function to find the longest common prefix string amongst an array of strings. 解答: 注意 ...
- Leetcode 14. Longest Common Prefix(水)
14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...
随机推荐
- perl 数组快速去除重复元素
这里记录两种perl数组去重的办法,一种利用哈希(hash),一种直接利用perl自带的模块List::MoreUtils内部的函数uniq. 一.利用hash去重 示例代码如下: 1 #!/usr/ ...
- 使用dumi生成react组件库文档并发布到github pages
周末两天玩了下号称西湖区东半球最牛逼的react文档站点生成工具dumi,顺带结合github pages生成了react-uni-comps文档站, 一套弄下来,感觉真香,现在还只是浅尝,高级的特性 ...
- C++中的排序
下面网站解释比较好 http://www.cnblogs.com/heyonggang/archive/2013/11/03/3404371.html 1. qsort(C中的函数加上stdlib.h ...
- Linux学习 - 条件判断
一.判断格式 test -e /root/install.log 或 [ -e /root/install.log ] 使用echo $?查看是否正确,当返回0时表示返回正确 1 按照文件类型进行判断 ...
- Kotlin 学习(2)
属性和字段 1.声明属性 Kotlin中可以使用var关键字声明可变属性,或者用val关键字声明只读属性,属性的类型在后面,变量名在前面,中间加冒号和空格. public class Address ...
- Linux:-e、-d、-f、-L、-r、-w、-x、-s、-h、
-e filename 如果 filename存在,则为真 -d filename 如果 filename为目录,则为真 -f filename 如果 filename为常规文件,则为真 -L fil ...
- Laravel框架角色、权限
角色表结构如下: 权限表结构如下: 控制器代码: //递归查询权限列表 public function index(){ $data = ManagePermissionModel::query()- ...
- spring security oauth2 搭建认证中心demo
oauth2 介绍 oauth2 协议应该是开发者们耳熟能详的协议了,这里就不做过多的介绍了,具体介绍如何在spring security中搭建oauth2的认证服务.Spring-Securit ...
- Linux实体服务器添加网卡
目录 一.简介 二.配置 三.添加网卡 四.总结 一.简介 服务器如果搭配了网口,在插入网线或者光纤后会亮灯.如果发现不亮,可以关闭机器查看亮不亮,因为有的时候系统会把网口禁用,进入到系统反而不亮了, ...
- 用 WinUI 3 开发了一个摸鱼应用
1. 开发了一个摸鱼 App 我做了一个简单的 App:摸鱼. 如上图所示,这个 App 就只有一个按钮,点击后假装开始 Windows Update,然后用户就可以光明正大地摸鱼了. 不要小看摸鱼, ...