3
1

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 5 years have passed since last update.

LeetCode / Longest Common Prefix

Posted at

ブログ記事からの転載)

[https://leetcode.com/problems/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 "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

全文字列共通のprefix(接頭辞)を見つける問題です。様々な解法があって、以下に紹介したもの以外も探してみると面白いと思います。

回答・解説

解法1

リストの1つ目の要素の最も長い文字列から順に確認していき、当てはまらなければ1文字削除してまた確認し・・・というiterationを回します。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs: return ''
        prefix = strs[0]
        for i in range(1,len(strs)):
            while not strs[i].startswith(prefix):
                prefix = prefix[0:len(prefix)-1]
                if not prefix: return ''
        return prefix

"flower"の例で言えば、"flower", "flowe", "flow", "flo", "fl"の順に確認していくことになります。

解法2

解法1は、リストの最初の文字列が最も長く、最後の文字列が最も短いような場合でも、初めの文字列数分のiterationを回してしまうことになります。
そこで、リストを横に見るのではなく、縦に見ることを考えます。
"flower"の例で言えば、"f", "fl", "flo", "flow", "flowe"の順に確認していくということです。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs: return ''
        for i in range(len(strs[0])):
            c = strs[0][i]
            for j in range(1, len(strs)):
                if i == len(strs[j]) or strs[j][i] != c:
                    return strs[0][:i]
        return strs[0]
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?