【leetcode每日一题】【2019-05-20】14. 最长公共前缀
2019-05-20 16:38
447 查看
14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。
Python3:
class Solution: def longestCommonPrefix(self, strs) -> str: comm_str="" if len(strs)==0: return "" if len(strs)==1: return strs[0] idx=1 flag=0 while 1==1 and flag==0 : tmp_str=strs[0][:idx] for i in strs: if not i.startswith(tmp_str) or idx>len(i): flag=1 break if flag==1: break comm_str=tmp_str idx=idx+1 return comm_str
Scala:
import scala.util.control.Breaks._ object Solution { def longestCommonPrefix(strs: Array[String]): String = { var comm_str="" if (strs.length==0){ return "" } var idx=1 var flag=0 breakable{ while (true && flag==0){ if (idx>strs(0).length){ break } var tmp_str=strs(0).substring(0,idx) print(tmp_str) strs.foreach{ i => if ( !i.startsWith(tmp_str) || idx > i.length() ){ flag=1 } } if (flag==1){ break } comm_str=tmp_str idx=idx+1 } } return comm_str } }
相关文章推荐
- Leetcode14. 最长公共前缀
- LeetCode14. 最长公共前缀
- [算法Rust,Go,Python,JS实现)]LeetCode之14-最长公共前缀
- Leetcode(14) 最长公共前缀
- 每日一练之Longest Common Prefix【LeetCode No.14】——求字符串的最长公共前缀
- LeetCode_Q14_最长公共前缀
- LeetCode14-最长公共前缀
- LeetCode题解(python)-14. 最长公共前缀
- leetcode14. 最长公共前缀
- leetcode-14-最长公共前缀
- LeetCode 14. 最长公共前缀
- LeetCode 14 Longest Common Prefix(最长公共前缀)(String)
- LeetCode14:最长公共前缀
- LeetCode 14 Longest Common Prefix(最长公共前缀)
- 【LeetCode】14. 最长公共前缀
- LeetCode-14.最长公共前缀
- LeetCode 14. 最长公共前缀
- Leetcode 14: 最长公共前缀(Longest Common Prefix)
- 【LeetCode】[14] 最长公共前缀
- LeetCode 14 最长公共前缀(字符串)