首页 > 代码库 > [leetcode]Longest Common Prefix @ Python
[leetcode]Longest Common Prefix @ Python
原题地址:https://oj.leetcode.com/problems/longest-common-prefix/
题意:Write a function to find the longest common prefix string amongst an array of strings.
解题思路:找出所有字符串共同的前缀。
代码:
class Solution: # @return a string def longestCommonPrefix(self, strs): if len( strs ) == 0: return ‘‘ if len( strs ) == 1: return strs[0] minstrslen = 9999 index = 0 for i in range( 0, len( strs ) ): if len( strs[i] ) < minstrslen: minstrslen = len( strs[i] ) index = i ShortestString = strs[index] list = [0 for i in range( len( ShortestString ) )] for i in range(0, len( ShortestString )): for j in range(0, len( strs )): if strs[j][i] == ShortestString[i]: list[i] += 1 Prefix = ‘‘ for i in range(0, len( ShortestString )): if list[i] == len( strs ): Prefix += ShortestString[i] else: break return Prefix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。