[LeetCode] Longest Common Prefix 最长共同前缀
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 最长共同前缀的更多相关文章
- LeetCode 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 ...
- # Leetcode 14:Longest Common Prefix 最长公共前缀
公众号:爱写bug Write a function to find the longest common prefix string amongst an array of strings. If ...
- 【LeetCode】14. Longest Common Prefix 最长公共前缀
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:prefix, 公共前缀,题解,leetcode, 力扣 ...
- [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 ...
- [LintCode] Longest Common Prefix 最长共同前缀
Given k strings, find the longest common prefix (LCP). Have you met this question in a real intervie ...
- Longest Common Prefix -最长公共前缀
问题:链接 Write a function to find the longest common prefix string amongst an array of strings. 解答: 注意 ...
随机推荐
- Scala集合和Java集合对应转换关系
作者:Syn良子 出处:http://www.cnblogs.com/cssdongl 转载请注明出处 用Scala编码的时候,经常会遇到scala集合和Java集合互相转换的case,特意mark一 ...
- 利用Python进行数据分析(10) pandas基础: 处理缺失数据
数据不完整在数据分析的过程中很常见. pandas使用浮点值NaN表示浮点和非浮点数组里的缺失数据. pandas使用isnull()和notnull()函数来判断缺失情况. 对于缺失数据一般处理 ...
- WCF Basics - FAQs Series【WCF基础----问答系列教程】
WCF学习系列一[WCF Interview Questions-Part 1 翻译系列] WCF学习系列二---[WCF Interview Questions – Part 2 翻译系列] WCF ...
- C#生成带logo的二维码
带logo的二维码生成分为两步骤:首先根据输入的内容生成二维码图片,然后读取本地的logo图片,通过图片处理生成带logo的二维码. 生成的二维码效果如下: 下面直接贴出二维码生成类 QRCode ...
- 在Winform界面菜单中实现动态增加【最近使用的文件】菜单项
在我们一些和文件处理打交道的系统中,我们往往需要记录下最近使用的文件,这样方便用户快速打开之前浏览或者编辑过的文件,这种在很多软件上很常见,本文主要介绍在Winform界面菜单中实现[最近使用的文件] ...
- ASP.NET MVC——CodeFirst开发模式
Entity Framework框架提供了几种开发模式,比如Database First,Model First,Code First.Database First是最老也是应用得最广泛的一种设计方式 ...
- jQuery Lightbox图片放大预览
简介:jQuery Lightbox图片放大预览代码是一款可以在用户点击页面中的小图片时,将该图片的高清版本以Lightbox的方式放大显示在页面的中间,提高用户的体验度. 效果展示 http://h ...
- [修正] Firemonkey Android 显示 Emoji (颜文字)
问题:在 Android 平台下,显示 Emoji 文字,无法显示彩色(皆为黑色),例如 Edit 控件,即使将 Edit.ControlType = Platform 设为平台原生控件,还是没用(真 ...
- redis 安装
安装wget http://download.redis.io/releases/redis-3.2.3.tar.gztar -xzvf redis-3.2.3.tar.gzcd redis-3.2. ...
- AlloyRenderingEngine之Shape
写在前面 不读文章,只对代码感兴趣可以直接跳转到这里 https://github.com/AlloyTeam/AlloyGameEngine 然后star一下,多谢支持:). 游戏或者应用中,不是所 ...