题目:Longest Common Prefix

内容:

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

  编写一个函数来查找字符串数组中最长的公共前缀字符串。

理解题目:

  如数组 ["a", "b"]   最长的公共前缀字符串是 “”;

  如数组 ["aa", "aa"]   最长的公共前缀字符串是 “aa”;

  如数组 ["abc", "abcd"]   最长的公共前缀字符串是 “abc”。。。

解题思路

 1 如果数组为空,则最长公共前缀为"";

 2 如果数组不为空:
(1)找出字符串数组中长度最短的字符串min,其长度为min_len; 因为最长的公共前缀长度不会超过min_len;
(2)遍历数组,将min位置为[i] 的字符 和 数组中其他字符串位置为[i]的字符 比较;
如果不相等,则最长公共前缀为 min的前i个字符;
如果都相等,则最长公共前缀为 min。

Go语言实现

 func longestCommonPrefix(strs []string) string {

     if len(strs) ==  {
return ""
} min_len := len(strs[])
index :=
for i:=; i<len(strs); i++ {
if len(strs[i]) < min_len {
min_len = len(strs[i])
index = i
}
} for j:=; j<len(strs[index]); j++ {
for k:=; k<len(strs); k++ {
if strs[index][j] != strs[k][j]{
return strs[index][:j]
}
}
}
return strs[index]
}

看一下耗时:

Python3实现

 class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortstr = min(strs, key=len)
for i, cha in enumerate(shortstr):
for other in strs:
if other[i] != cha:
return shortstr[:i]
return shortstr

看一下耗时:

是不是感觉go要快很多,Python更优雅?

最新文章

  1. 超简单——自己搭建ftp服务器
  2. tp5 model 中的类型转换
  3. 在Winform开发中使用日程控件XtraScheduler(2)--深入理解数据的存储
  4. 做中学之Vim实践教程
  5. 深入JVM-java虚拟机的基本结构
  6. ant学习
  7. WPF:ListView数据绑定及Style
  8. [wordpress]后台自定义菜单字段和使用wordpress color picker
  9. SWFUpload无刷新文件批量上传
  10. 洛谷 [P2764]最小路径覆盖问题
  11. codeblocks设置背景主题
  12. Ubuntu下安装Pycharm出现unsupported major.minor version 52.0
  13. C++系列总结——volatile关键字
  14. 微信小程序--家庭记账本开发--05
  15. jvm调优-从eclipse开始
  16. Unity中的GC以及优化
  17. 【转】android中的数据存取-方式一:preference(配置)
  18. chattr lsattr
  19. MyEclipse自带且常用的快捷键和自己定义的快捷键方法步骤
  20. CSS的基本使用

热门文章

  1. Hibernate Error: a different object with the same identifier value was already associated with the session
  2. Eventlog控件的使用
  3. nyoj281 整数中的1(二) 数位DP
  4. react——一个todolist的demo
  5. jQuery手机发送验证码倒计时代码
  6. RS232 3线制与7线制的区别
  7. mysql常用基础操作语法(六)--对数据排序和限制结果数量的条件查询【命令行模式】
  8. HashMap和Hashtable的异同点
  9. String getProperty(String key, String def)
  10. Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column &#39;content&#39; a