0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

leet code easy Longest Common Prefix

Posted at

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:
#sizeにstrsの要素数を入れる。0、1の時は固定で返す。
        size = len(strs)
        if len(strs) == 0:
            return ""
        if len(strs) == 1:
            return strs[0]
#sort()でアルファベット順に並べ替える。
        strs.sort()
#minで一番短い単語をendに入れる。
        end = min(len(strs[0]),len(strs[size - 1]))
        i = 0
#最短の単語の文字数までの中で、strs[0][i]==strs[size-1][i](最初と最後の単語=最もアルファベット順で異なっている2つの、[i]番目の数字が同じか探索していく。))
        while (i < end and strs[0][i]==strs[size-1][i]):
            i += 1
#最初の単語の、1文字目からi文字目(共通文字の最後)までをreturnする
        pre = strs[0][0:i]
        return pre
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?