Longest common prefix (Python)

Write a function to find the longest common prefix string array.

If there is no common prefix, it returns an empty string "."

Example 1:

Input: [ "flower", "flow ", "flight"]
Output: "fl"
Example 2:

Input: [ "dog", "racecar ", "car"]
Output: ""
Explanation: there is no input common prefix.
Description:

All input contains only lowercase letters az.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-common-prefix
I did the title of the most wanted to start with the first character to match all strings, found a flaw :

When a character string length than the first and smaller matching error will occur, so the minimum point is determined as the length of the list.

Solution class: 
DEF longestCommonPrefix (Self, strs):
IF len (strs) == 1: # Only a return array of strings itself.
STRs return [0]
if len (STRs) == "" or STRs == []:
return ""
A = len (STRs)
n-A =. 1-
the while n-> = 0: # descending order
if len ( STRs [n-]) <len (STRs [n--. 1]):
S = STRs [n-]
STRs [n-] = STRs [n--. 1]
STRs [n--. 1] = S
n-- =. 1
B = len (STRs [len (strs) -1]) # obtain a minimum length of string length, and to ensure that the last array of strings shortest
J = 0
P = 0
iF B <= 0: # 0 when a length equal to the minimum, so there is no common prefix.
return ""
the while True:
STRs the while [0] [J] = STRs [P +. 1] [J]:!
IF STRs [0] [: J] == None:
return ""
the else:
return STRs [0] [: J]
P = + . 1
iF P> =. 1-a:
j =. 1 +
P = 0
iF j == len (STRs [-P. 1]): # when j is equal to the shortest length of the string returned directly
return strs [0] [: j ]

Guess you like

Origin www.cnblogs.com/justkeep/p/11519119.html
Recommended