[LeetCode] 14. 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] 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】14. Longest Common Prefix 最长公共前缀
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:prefix, 公共前缀,题解,leetcode, 力扣 ...
- 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】Longest Common Prefix(最长公共前缀)
这道题是LeetCode里的第14道题. 题目描述: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["f ...
- Leetcode 14. Longest Common Prefix(水)
14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...
- # 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 最长前缀子串
题目: Write a function to find the longest common prefix string amongst an array of strings. 思路:求最长前缀子 ...
- [LeetCode] Longest Common Prefix 最长共同前缀
Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...
随机推荐
- POJ-2006 Litmus Test 高精度
The pH scale measures the concentration of protons (H +) in a solution and, therefore, its acidity o ...
- Vue.js安装及环境搭建
Vue.js环境搭建-Windows版 步骤一:安装node.js 在搭建vue的开发环境之前,需要先下载node.js,vue的运行是要依赖于node的npm的管理工具来实现,node可以在官网或者 ...
- Spring Cloud Hystrix 熔断器(五)
序言 感觉hystrix很精彩,文档讲的也很好,这篇总结到哪里是哪里吧 写Hystrix之前,我们先简单的说说熔断器,和限流,这样你看完之后,就可以很容易理解Hystrix 熔断器 熔断器模式源于Ma ...
- SSM手动实现分页逻辑---非PageHelper方式
第一种方法:查询出所有数据再分页 分析: 分页时,需要获得前台传来的两个参数,分别为pageNo(第几页数据),pageSize(每页的条数); 根据这两个参数来计算出前端需要的数据是查出数据list ...
- MySQL for OPS 06:备份恢复
写在前面的话 人在河边走,湿鞋是早晚是事情,操作服务器,数据库也一样.谁也不知道自己哪一天控制不住自己就手贱.这时候有两个东西能救我们,一是备份,二是 bin log,bin log 前面讲了,但是 ...
- Java中级知识归纳(四)
十六.Java内存模型 特点:原子性.可见性.有序性. 原子性:read.load.use.store.write.synchronized关键字保证原子性 可见性:synchronized.vola ...
- python time包中的time.time()和time.clock()的区别
在统计python代码 执行速度时要使用到time包,在查找相关函数时有time.time()和time.clock()两个函数可供选择.而两者是有区别的: cpu 的运行机制:cpu是多任务的,例如 ...
- 百度地图分布图(百度地图api司机位置实时定位分布图)
就类似于我们使用共享单车app的时候,可以看到我们周围的空闲单车分布.e代驾在后台管理系统需求里也有此功能,目的是为了实时看到目标城市下的所有司机状态. 一.controller //controll ...
- Laravel 运行php artisan serve命令时提示No application encryption key has been specified
创建了新的laravel项目后, 运行提示:No application encryption key has been specified 解决方法: 这个是由于没有配置好 APP_KEY 在终端上 ...
- 蜂鸟E203 IFU模块
E203的IFU(instruction fetch unit)模块主要功能和接口如下: IFU的PC生成单元产生下一条指令的PC. 该PC传输到地址判断和ICB生成单元,就是根据PC值产生相应读指请 ...