Python活力练习Day17
Day17:查找字符串最长公共前缀
eg1: input : ["folwer", "flow", "flight"]
output : "fl"
eg2: input : ["dog", "racecar" , "car"]
output : 空
#利用python中的 Max()和 Min()函数,在Python中字符串可以相比较。按照ASCII排,举例:'abb','aba','abac'最大为'abb',最小为‘aba’,所以只需要比较最大最小字符串的公共前缀即可
#红色部分的解释:按照ASCII码,
a | b | b | 1 | |
a | b | a | 3 | |
a | b | a | c | 2 |
相等 | 相等 | b大 | c大 |
#Python中,if not 判断变量是否为None(none 代表有空字符串,0,空列表,空字典,空元祖):
if strs is none
if not strs
if not (strs is none)
#需要用到的ASCII码:
ASCII码 | ||
字母 | a-z | 97-122 |
A-Z | 65-90 | |
数字 | 0-9 | 48-57 |
1 def longestCommonPrefix(strs): 2 if not strs: 3 return " " 4 s1 = min(strs) 5 s2 = max(strs) 6 for i,x in enumerate(s1): 7 if x != s2[i]: 8 return s2[:i] 9 return s1 10 11 if __name__ == "__main__": 12 strs = ["flower", "flow", "flight"] 13 strs1 = ["dog", "racecar" , "car"] 14 print(longestCommonPrefix(strs)) 15 print(longestCommonPrefix(strs1))
输出结果: