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:

  1. Input: ["flower","flow","flight"]
  2. Output: "fl"

Example 2:

  1. Input: ["dog","racecar","car"]
  2. Output: ""
  3. 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++ 解法一:

  1. class Solution {
  2. public:
  3. string longestCommonPrefix(vector<string>& strs) {
  4. if (strs.empty()) return "";
  5. string res = "";
  6. for (int j = ; j < strs[].size(); ++j) {
  7. char c = strs[][j];
  8. for (int i = ; i < strs.size(); ++i) {
  9. if (j >= strs[i].size() || strs[i][j] != c) {
  10. return res;
  11. }
  12. }
  13. res.push_back(c);
  14. }
  15. return res;
  16. }
  17. };

Java 解法一:

  1. public class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if (strs == null || strs.length == 0) return "";
  4. String res = new String();
  5. for (int j = 0; j < strs[0].length(); ++j) {
  6. char c = strs[0].charAt(j);
  7. for (int i = 1; i < strs.length; ++i) {
  8. if (j >= strs[i].length() || strs[i].charAt(j) != c) {
  9. return res;
  10. }
  11. }
  12. res += Character.toString(c);
  13. }
  14. return res;
  15. }
  16. }

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

C++ 解法二:

  1. class Solution {
  2. public:
  3. string longestCommonPrefix(vector<string>& strs) {
  4. if (strs.empty()) return "";
  5. for (int j = ; j < strs[].size(); ++j) {
  6. for (int i = ; i < strs.size(); ++i) {
  7. if (j >= strs[i].size() || strs[i][j] != strs[][j]) {
  8. return strs[i].substr(, j);
  9. }
  10. }
  11. }
  12. return strs[];
  13. }
  14. };

Java 解法二:

  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if (strs == null || strs.length == 0) return "";
  4. for (int j = 0; j < strs[0].length(); ++j) {
  5. for (int i = 0; i < strs.length; ++i) {
  6. if (j >= strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)) {
  7. return strs[i].substring(0, j);
  8. }
  9. }
  10. }
  11. return strs[0];
  12. }
  13. }

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

C++ 解法三:

  1. class Solution {
  2. public:
  3. string longestCommonPrefix(vector<string>& strs) {
  4. if (strs.empty()) return "";
  5. sort(strs.begin(), strs.end());
  6. int i = , len = min(strs[].size(), strs.back().size());
  7. while (i < len && strs[][i] == strs.back()[i]) ++i;
  8. return strs[].substr(, i);
  9. }
  10. };

Java 解法三:

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

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 最长共同前缀的更多相关文章

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

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

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

  5. 【LeetCode】Longest Common Prefix(最长公共前缀)

    这道题是LeetCode里的第14道题. 题目描述: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["f ...

  6. Leetcode 14. Longest Common Prefix(水)

    14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...

  7. # Leetcode 14:Longest Common Prefix 最长公共前缀

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

  8. 【LeetCode】14. Longest Common Prefix 最长前缀子串

    题目: Write a function to find the longest common prefix string amongst an array of strings. 思路:求最长前缀子 ...

  9. [LeetCode] Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. 这道题让我们求一系列字符串 ...

随机推荐

  1. Leetcode练习题 7. Reverse Integer

    7. Reverse Integer 题目描述: Given a 32-bit signed integer, reverse digits of an integer. Example 1: Inp ...

  2. 使用 jQuery.TypeAhead 让文本框自动完成 (一)(最简单的用法)

    项目地址:https://github.com/twitter/typeahead.js 直接贴代码了: @section headSection { <script type="te ...

  3. C# 多线程处理List数据

    代码思路 将要处理的数据放到ConcurrentQueue中,然后开启多个线程去处理数据,处理完成后,再到队列中获取下一个待处理数据. ConcurrentQueue 表示线程安全的先进先出 (FIF ...

  4. EntityUtils.toString(entity)处理字符集问题解决

    爬取51Job和猎聘网的信息,想处理字符集问题(51job为gbk,猎聘为utf-8), 找到两个网站字符集信息都在同一标签下 就想先把网页保存成String,解析一遍获取字符集,然后将网页转换成对应 ...

  5. Class文件和JVM的恩怨情仇

    类的加载时机 现在我们例子中生成的两个.class文件都会直接被加载到JVM中吗?? 虚拟机规范则是严格规定了有且只有5种情况必须立即对类进行“初始化”(class文件加载到JVM中): 创建类的实例 ...

  6. es6中find方法

    find() 方法返回数组中满足提供的测试函数的第一个元素的值.否则返回 undefined. , , , , ]; var found = array1.find(function(element) ...

  7. 21个React开发神器

    摘要: React开发神器. 原文:22 Miraculous Tools for React Developers in 2019 译者:前端小智 下列工具中的重要性与排序无关. 1.Webpack ...

  8. SQL Server学习内容(一)

    SQL Server SQL Server对大小写不敏感,每条语句末端使用分号. 1.SQL命令 SELECT 从数据中提取数据 UPDATE 更新数据中的数据 DELETE 从数据库中删除数据 IN ...

  9. linux 线程基础

    线程基础函数 查看进程中有多少个线程,查看线程的LWP ps -Lf 进程ID(pid) 执行结果:LWP列 y:~$ ps -Lf 1887 UID PID PPID LWP C NLWP STIM ...

  10. Git学习笔记3-远程仓库

    1.添加远程仓库 $ git remote add [shortname] [url] $ git remote add origin https://github.com/Mike199201/Gi ...