免責事項:この記事はブロガーオリジナル記事です、続くBY-SAのCC 4.0を著作権契約、複製、元のソースのリンクと、この文を添付してください。
[LeetCode] 14.最長共通接頭辞の問題解決レポート(パイソン)
トピック住所:https://leetcode.com/problems/longest-common-prefix/
タイトル説明
文字列の配列の中で最長の共通のプレフィックスの文字列を検索する関数を書きます。
共通の接頭辞がない場合は、「」空の文字列を返します。
例1:
Input: ["flower","flow","flight"]
Output: "fl"
例2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
解決方法1:並べ替え、最初の文字列を比較します
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
strs.sort()
size = min(len(strs[0]), len(strs[-1]))
i = 0
while i < size and strs[0][i] == strs[-1][i]:
i += 1
return strs[0][:i]
解決方法2:ソリューションの暴力、文字列トラバーサルの最小の長さに基づいて、
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs or not min([len(str) for str in strs]):
return ""
for i in range(min([len(str) for str in strs])):
pre = strs[0][i]
if not all(str[i] == pre for str in strs):
i -= 1
break
return strs[0][:i+1]
分サプリメントの使用状況
pre = min(strs, key = len) # 求最小长度字符串