直接上代码:
1 def longestCommonPrefix(strs): 2 """ 3 :type strs: List[str] 4 :rtype: str 5 """ 6 str_list = strs 7 if len(str_list) > 1: 8 s_last = str_list.pop() 9 common_str = '' 10 common = '' 11 for num, str_ in enumerate(str_list): 12 if num is 0: 13 if len(s_last) >= len(str_): 14 len_str = len(str_) 15 else: 16 len_str = len(s_last) 17 for i,j in enumerate(range(len_str)): 18 if s_last[i] == str_[i]: 19 common_str += s_last[i] 20 else: 21 break 22 if not common_str: 23 return '' 24 else: 25 if len(common_str) >= len(str_): 26 len_str = len(str_) 27 else: 28 len_str = len(common_str) 29 for i,j in enumerate(range(len_str)): 30 if common_str[i] == str_[i]: 31 common = common_str[:i+1] 32 else: 33 common = common_str[:i] 34 if len(str_list) is 1: 35 return common_str 36 else: 37 return common 38 if len(str_list) is 1: 39 return common_str 40 else: 41 return common 42 elif len(str_list) is 1: 43 return str_list[0] 44 else: 45 return ''