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?

14. Longest Common Prefix の要点

Posted at

問題内容

単語のリストが入力されたら、その接頭辞について共通箇所を出力するように書き加えなさいというもの。なければ""と出力する。

解答例

sample
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        ans = ""
        v=sorted(strs)
        first=v[0]
        last=v[-1]
        for i in range(min(len(first),len(last))):
            if(first[i]!=last[i]):
                return ans
            ans+=first[i]
        return ans

この問題の要点

  • リストをソートをすると、最初と最後の単語だけで文字が共通するか否かの比較が済む
  • 単語に含まれるそれぞれの文字には、以下のように書くことでアクセスできる
fisrt[i]
  • 比較する2つの単語のうち少ない文字数にループ回数を設定するとエラーを回避できる
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?