Day17: Find the longest common prefix string
eg1: input : ["folwer", "flow", "flight"]
output : "fl"
eg2: input : ["dog", "racecar" , "car"]
output : 空
# Python using the Max () and Min () function, may be compared to a string in Python. The ASCII row, for example: 'abb', 'aba', 'ABAC' maximum 'abb', minimum 'ABA' , you only need to compare the maximum to minimum common prefix string
# Red part of the explanation: the ASCII code,
a | b | b | 1 | |
a | b | a | 3 | |
a | b | a | c | 2 |
equal | equal | big b | c large |
#Python in, if not determined whether the variable None (none available behalf string, 0, empty list, empty dictionary, null Zu):
if strs is none
if not strs
if not (strs is none)
# Need to use the ASCII code:
ASCII code | ||
letter | a-z | 97-122 |
A-Z | 65-90 | |
digital | 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))
Output: