公众号:爱写bug

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.

说明:

所有输入只包含小写字母 a-z

解题思路Java:

​ 很简单又很经典的一道题,我的思路起先是 把第字符串组第一个字符串转为char型。利用StringBuilder逐一累加相同字符。由于字符串长度不一,可以先遍历找出最小长度字符串,这里我选择抛错的形式,减少一次遍历。

代码:

class Solution {
public String longestCommonPrefix(String[] strs) {
int strLen=strs.length;
if(strLen==0) return "";//空字符串组返回""
char[] temp=strs[0].toCharArray();
StringBuilder str = new StringBuilder();
for (int i=0;i<strs[0].length();i++){//以第一个字符串长度开始比较
for (int j=1;j<strLen;j++){
try {
if(temp[i]!=strs[j].charAt(i)){
return str.toString();
}
}catch (IndexOutOfBoundsException e){//抛出错误,这里错误是指索引超出字符串长度
return strs[j];
}
}
str.append(temp[i]);
}
return strs[0];
}
}

​ 后面想到Java有 subString() 方法,可指定长度截取字符串,无需转为 char[] 型,但是在 Leetcode 提交时反而不如上面这种方式运算快,这也说明了Java不支持运算符重载,使用 substring() 每次新建一个String字符串,效率并不高。

​ 最后看到一个方法,大致思路是找到最小长度字符串,从大到小截取字符串,既然用到 subString() 方法,不如就从后向前,因为题目是找出最长公众前缀,从大到小效率很高。具体请看:

 public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0) return "";
int min=Integer.MAX_VALUE;
String minStr="";
for(int i=0;i<strs.length;i++){//找出最小长度字符串
if(min>strs[i].length()){
minStr=strs[i];
min=strs[i].length();
}
}
if(min==0) return "";
for(int i=min;i>=0;i--){//最小长度字符串从长到短截取
String standard=minStr.substring(0, i);
int j=0;
for(j=0;j<strs.length;j++){
if(strs[j].substring(0, i).equals(standard)) continue;
else break;
}
if(j==strs.length) return standard;
}
return "";
}
}

原代码链接: https://blog.csdn.net/qq_14927217/article/details/72955791

解题思路py3:

​ 再次投机取巧,os.path 封装函数 commonprefix() 一步到位。

代码:

class Solution(object):
def longestCommonPrefix(self, strs):
import os
return os.path.commonprefix(strs)

​ 其实该函数是利用ASCll码比较的特性来编写的,源码:

def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
# Some people pass in a list of pathname parts to operate in an OS-agnostic
# fashion; don't try to translate in that case as that's an abuse of the
# API and they are already doing what they need to be OS-agnostic and so
# they most likely won't be using an os.PathLike object in the sublists.
if not isinstance(m[0], (list, tuple)):
m = tuple(map(os.fspath, m))
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1)://枚举得到s1的每一个字符及其索引
if c != s2[i]:
return s1[:i]
return s1

尽管如此,py3这段代码的执行速度依然远比Java慢的多。

注:ASCll码比较大小并非是按照所有字符的ASCll累加之和比较,是从一个字符串第一个字符开始比较大小,如果不相同直接得出大小结果,后面的字符不在比较。

# 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] 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】Longest Common Prefix(最长公共前缀)

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

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

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

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

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

  9. Leetcode 14. Longest Common Prefix(水)

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

随机推荐

  1. SqLite踩的坑

    一.修改表名称.增加字段.查询表结构.修改表结构字段类型 .修改表名称 ALTER TABLE 旧表名 RENAME TO 新表名 eg: ALTER TABLE or_sql_table RENAM ...

  2. Winfrom中设置ZedGraph显示多个标题(一个标题换行显示)效果

    场景 Winforn中设置ZedGraph曲线图的属性.坐标轴属性.刻度属性: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...

  3. asp.net发布后其他电脑部署——未能加载文件或程序集 System.Web.Mvc, Version=2.0.0.0, Culture=neutral,

    本机测试及发布使用正常 在项目中添加了引用但相关dll文件未在bin文件夹中 导致发布后部署其他电脑未能加载程序集 网上说要下载相关内容在部署服务器安装 但怕在服务器安装出现其他问题 所以在项目中重新 ...

  4. Python 摘要算法hashlib 与hmac

    参考链接:https://www.liaoxuefeng.com/wiki/1016959663602400/1017686752491744 摘要算法(也成为哈希算法)是用来防篡改的,因为我们的即使 ...

  5. js数组试列题

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  6. 大白话说GIT常用操作,常用指令git操作大全

    列一下在开发中用的比较多的git指令 git clone https://github.com/chineseLiao/Small-career // 克隆远程仓库到本地 git add . // 把 ...

  7. Git内部原理浅析

    Git独特之处 Git是一个分布式版本控制系统,首先分布式意味着Git不仅仅在服务端有远程仓库,同时会在本地也保留一个完整的本地仓库(.git/文件夹),这种分布式让Git拥有下面几个特点: 1.直接 ...

  8. iOS 快速打包方法

    这种打包方式应该是目前所有打包方式中最快的,就是编译工程--找到.app文件--新建Payload文件夹--拷贝.app到Payload文件夹--压缩成zip--更改后缀名为ipa--完成! 注意事项 ...

  9. 智能家居-2.基于esp8266的语音控制系统(硬件篇)

    智能家居-1.基于esp8266的语音控制系统(开篇) 智能家居-2.基于esp8266的语音控制系统(硬件篇) 智能家居-3.基于esp8266的语音控制系统(软件篇) 赞赏支持 QQ:505645 ...

  10. scp文件拷贝简易使用

    scp远程复制 属性变化 需要复制所属关系需要用-p选项 源目录复制之后目的目录的属性: srcdrwxr-xr-x. 2 root root 6 9月 4 16:28 2.txt dstdrwxr- ...