[PYTHON] leet code easy Longest Common Prefix

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 "".

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
#Enter the number of elements of strs in size. When it is 0 or 1, it is fixedly returned.
        size = len(strs)
        if len(strs) == 0:
            return ""
        if len(strs) == 1:
            return strs[0]
#sort()Sort alphabetically with.
        strs.sort()
#Put the shortest word in min into end.
        end = min(len(strs[0]),len(strs[size - 1]))
        i = 0
#Strs up to the shortest number of characters[0][i]==strs[size-1][i](Firstandlastwords=thetwomostalphabeticallydifferent,[i]Searchforthesamesecondnumber.))
        while (i < end and strs[0][i]==strs[size-1][i]):
            i += 1
#Return from the first letter to the i-th letter (the end of the common letter) of the first word
        pre = strs[0][0:i]
        return pre

Recommended Posts

leet code easy Longest Common Prefix
leet code Palindrome Number (easy)
Let Code Day47 Starting from Zero "14. Longest Common Prefix"
leet code easy Roman to Integer Approach 1: Left-to-Right Pass
I tried LeetCode every day 14.Longest Common Prefix (Python, Go)