声明:
如标题所示,因本人为AI路上的新手,文章用于辅助个人的整理记忆,理解难免有偏差之处,都是个人拙见,如给其他同僚造成困扰,还请见谅,非常非常非常欢迎私信共同讨论,共同进步
题目描述:
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.
少废话,上代码:
class Solution:
def longestCommonPrefix(self, s):
ans = ""#定义一个空的字符,来放置相同的前缀
#以下两个if语句,是原题会出现的一些特殊情况,剔除掉
#无较高的算法意义
if s == []:
return ans
if len(s) == 1:
return s[0]
min_l = len(s[0])#欲找出整个列表中,长度最短的那个元素,作为外循环的限制
for l in s:
if len(l) < min_l:
min_l = len(l)#必须是最短的那一个,否则会超出索引范围
for i in range(min_l):#外循环,默认第一个字符是共有的,每次向后移动一个
init = s[0][i]
for j in range(1, len(s)):#内循环,每次遍历整个列表,检查每个元素是否一致
if init != s[j][i]:#如遇不等,直接返回ans
return ans
if init == s[j][i] and j == len(s) - 1:#仅当相等且内循环结束时,才可将此字符算作是相同的
ans += init
return ans
时间空间复杂度:
- Runtime: 36 ms, faster than 34.04% of Python3 online submissions for Longest Common Prefix.
- Memory Usage: 13 MB, less than 98.10% of Python3 online submissions for Longest Common Prefix.