Leet code刷題筆記

Longest Common Prefix -Python解題

困難度:Easy

題目: 在一系列字串中,找出相同的前綴字,如都沒有,則打印空字串。

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: strs = [“flower”,“flow”,“flight”]

Output: “fl”

Example 2:

Input: strs = [“dog”,“racecar”,“car”]

Output: ""

Explanation: There is no common prefix among the input strings.

Python解題筆記

Inline code has back-ticks around it.

class Solution:
    def longestCommonPrefix(self, strs):
        for i in range(len(strs[0])):
            for s in strs[1:]:
                if i>=len(s) or s[i] != strs[0][i] :
                    return strs[0][:i]
        if not strs:
            return ""
        return strs[0]

題目原處-LeetCode