【Leetcode】|pythonプログラミング思考練習-最長共通接頭辞
2910 ワード
タイトルの要件:
文字列配列の最長の共通接頭辞を検索する関数を作成します.
最長の共通接頭辞が存在しない場合は、空の文字列「」を返します.
例:例1:入力:["flower","flow","flight"]出力:「fl」 例2:入力:["dog","racecar","car"]出力:"" 解釈:入力に最長の共通接頭辞は存在しません. 説明:すべての入力には小文字a-zのみが含まれます.
サンプルコード:
考え方: strsが空の場合、空の文字列を返します. 最長の共通接頭辞を探して、max(strs)とmin(strs)を比較するだけです. テクニックポイント:文字列は最小値を求め、文字のASCIIコードに基づいてソートされます.
最も簡潔な方法
文字列配列の最長の共通接頭辞を検索する関数を作成します.
最長の共通接頭辞が存在しない場合は、空の文字列「」を返します.
例:
サンプルコード:
考え方:
# 1:
min(["hello", 'abc', 'he']) # "abc";
# 2:
min(['a', 'abc', 'ae']) # "ae"
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# strs , ;
if not strs: return ''
# , ;
s1 = min(strs)
s2 = max(strs)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
最も簡潔な方法
import os
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# ;
return os.path.commonprefix(strs)