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.

这道题让我们求一系列字符串的共同前缀,没有什么特别的技巧,无脑查找即可,定义两个变量i和j,其中i是遍历搜索字符串中的字符,j是遍历字符串集中的每个字符串。这里将单词上下排好,则相当于一个各行长度有可能不相等的二维数组,遍历顺序和一般的横向逐行遍历不同,而是采用纵向逐列遍历,在遍历的过程中,如果某一行没有了,说明其为最短的单词,因为共同前缀的长度不能长于最短单词,所以此时返回已经找出的共同前缀。每次取出第一个字符串的某一个位置的单词,然后遍历其他所有字符串的对应位置看是否相等,如果有不满足的直接返回 res,如果都相同,则将当前字符存入结果,继续检查下一个位置的字符,参见代码如下:

C++ 解法一:

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
string res = "";
for (int j = ; j < strs[].size(); ++j) {
char c = strs[][j];
for (int i = ; i < strs.size(); ++i) {
if (j >= strs[i].size() || strs[i][j] != c) {
return res;
}
}
res.push_back(c);
}
return res;
}
};

Java 解法一:

public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String res = new String();
for (int j = 0; j < strs[0].length(); ++j) {
char c = strs[0].charAt(j);
for (int i = 1; i < strs.length; ++i) {
if (j >= strs[i].length() || strs[i].charAt(j) != c) {
return res;
}
}
res += Character.toString(c);
}
return res;
}
}

我们可以对上面的方法进行适当精简,如果发现当前某个字符和第一个字符串对应位置的字符不相等,说明不会再有更长的共同前缀了,直接通过用 substr 的方法直接取出共同前缀的子字符串。如果遍历结束前没有返回结果的话,说明第一个单词就是公共前缀,返回为结果即可。代码如下:

C++ 解法二:

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
for (int j = ; j < strs[].size(); ++j) {
for (int i = ; i < strs.size(); ++i) {
if (j >= strs[i].size() || strs[i][j] != strs[][j]) {
return strs[i].substr(, j);
}
}
}
return strs[];
}
};

Java 解法二:

class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
for (int j = 0; j < strs[0].length(); ++j) {
for (int i = 0; i < strs.length; ++i) {
if (j >= strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)) {
return strs[i].substring(0, j);
}
}
}
return strs[0];
}
}

我们再来看一种解法,这种方法给输入字符串数组排了个序,想想这样做有什么好处?既然是按字母顺序排序的话,那么有共同字母多的两个字符串会被排到一起,而跟大家相同的字母越少的字符串会被挤到首尾两端,那么如果有共同前缀的话,一定会出现在首尾两端的字符串中,所以只需要找首尾字母串的共同前缀即可。比如例子1排序后为 ["flight", "flow", "flower"],例子2排序后为 ["cat", "dog", "racecar"],虽然例子2没有共同前缀,但也可以认为共同前缀是空串,且出现在首尾两端的字符串中。由于是按字母顺序排的,而不是按长度,所以首尾字母的长度关系不知道,为了防止溢出错误,只遍历而这种较短的那个的长度,找出共同前缀返回即可,参见代码如下:

C++ 解法三:

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

Java 解法三:

class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == ) return "";
Arrays.sort(strs);
int i = , len = Math.min(strs[].length(), strs[strs.length - ].length());
while (i < len && strs[].charAt(i) == strs[strs.length - ].charAt(i)) i++;
return strs[].substring(, i);
}
}

Github 同步地址:

https://github.com/grandyang/leetcode/issues/14

参考资料:

https://leetcode.com/problems/longest-common-prefix

https://leetcode.com/problems/longest-common-prefix/discuss/6910/Java-code-with-13-lines

https://leetcode.com/problems/longest-common-prefix/discuss/6940/Java-We-Love-Clear-Code!

https://leetcode.com/problems/longest-common-prefix/discuss/6926/Accepted-c%2B%2B-6-lines-4ms

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Longest Common Prefix 最长共同前缀的更多相关文章

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

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

  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 14:Longest Common Prefix 最长公共前缀

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

  4. 【LeetCode】14. Longest Common Prefix 最长公共前缀

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

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

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

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

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

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

  8. [LintCode] Longest Common Prefix 最长共同前缀

    Given k strings, find the longest common prefix (LCP). Have you met this question in a real intervie ...

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

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

随机推荐

  1. Events基本概念----Beginning Visual C#

    span.kw { color: #007020; font-weight: bold; } code > span.dt { color: #902000; } code > span. ...

  2. 用struts2标签如何从数据库获取数据并在查询页面显示。最近做一个小项目,需要用到struts2标签从数据库查询数据,并且用迭代器iterator标签在查询页面显示,可是一开始,怎么也获取不到数据,想了许久,最后发现,是自己少定义了一个变量,也就是var变量。

    最近做一个小项目,需要用到struts2标签从数据库查询数据,并且用迭代器iterator标签在查询页面显示,可是一开始,怎么也获取不到数据,想了许久,最后发现,是自己少定义了一个变量,也就是var变 ...

  3. 版本控制工具Git的学习笔记

    在网上看到一个很不错的Git教程,学习后果断要做一下总结. 教程地址:http://www.liaoxuefeng.com/ 总结要点: 安装Git因为我个人的开发主要是基于windows环境下,所以 ...

  4. Redis命令拾遗三(列表List类型)

    本文版权归博客园和作者吴双本人共同所有.转载和爬虫请注明原文地址 Redis五种数据类型之列表类型 Redis五种数据类型之列表类型.你可以存储一个有序的字符串列表一类数据.比如你想展示你所存储的所有 ...

  5. 记录一次bug解决过程:resultType和手动开启事务

    一.总结 二.BUG描述:MyBatis中resultType使用 MyBatis中的resultType类似于入参:parameterType.先看IDCM项目中的实际使用案例代码,如下: // L ...

  6. A2W、W2A、A2T、T2A的使用方法

    1.A2W和W2A 在<Window核心编程>,多字节和宽字节之间转换比较麻烦的,MultiByteToWideChar函数和WideCharToMultiByte函数有足够多的参数的意义 ...

  7. 浏览器对localstorage的支持情况以及localstorage在saas系统中的应用实践思考

    首先,还是要说,任何一种新特性的引入,通常有着其特有的场景和解决的目标需求,localstorage也一样.在我们的应用场景中,主要在金融业务服务的saas系统.其中涉及很多更改频率很多的元数据的客户 ...

  8. WCF服务启用与配置端口共享

    在 Windows Communication Foundation (WCF) 应用程序中使用 net.tcp:// 端口共享的最简单方式是使用 NetTcpBinding 公开一个服务. 此绑定提 ...

  9. 几句话就能让你理解:this、闭包、原型链

    以下是个人对这三个老大难的总结(最近一直在学习原生JS,翻了不少书,不少文档,虽然还是新手,但我会继续坚持走我自己的路) 原型链 所有对象都是基于Object.prototype,Object.pro ...

  10. Android开发学习—— ContentProvider内容提供者

    * 应用的数据库是不允许其他应用访问的* 内容提供者的作用就是让别的应用访问到你的数据库.把私有数据暴露给其他应用,通常,是把私有数据库的数据暴露给其他应用. Uri:包含一个具有一定格式的字符串的对 ...