一、题目描述(最长公共前缀)
https://leetcode.com/problems/longest-common-prefix/description/
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
.
二、题目分析
遍历字符串数组中的字符串,找到每两个字符串的最大公共前缀,保存为str1,继续用str1与接下来的字符串比较,找到str1与接下来的字符串的最大公共前缀,保存,遍历一遍可以得出结果。
注意:for循环次数问题和字符串的位数问题,焦头烂额·········
三、代码实现
class Solution(object): def longestCommonPrefix(self,strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' str1 = strs[0] #str1设置初始值为第一个字符串 for i in range(len(strs)-1): #遍历每一个字符串 str2 = strs[i + 1] #str2为下一个需要便利的字符串 for j in range(len(strs[0])-1,-2,-1): #遍历字符串的每一位 if str1 == strs[i+1][0:len(str1)]:break #如果下一个字符串中有与第一个字符串相匹配的前缀,则跳出第二层循环 str1=strs[i][0:j] #str1从最长开始,逐步缩小一位 return str1