1. 程式人生 > >LeetCode14:Longest Common Prefix

LeetCode14: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.


LeetCode:連結

這題和最長公共子串和和最長公共子序列很像,但是簡單的多。因為要找的是共同的prefix,字首是從第0位開始往後找,如果第0位就不一樣,後面即使一樣也不匹配

思想是以strs中第一字串為模板,每次比較其字元與其他字串相同位置的字元,並且判斷沒有超過字串的長度。

  1. 選取第一個字串作為最長公共字首
  2. 遍歷這個字首的每個字元
  3. 若所有的字串都含有這個字元,則最長公共字首指標前進1
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ""
        '''選第一個字串作為匹配模板'''
        prefix = strs[0]
        '''確定至少需要遍歷的長度'''
        length = len(prefix)
        '''判斷其他字串'''
        for i in range(1, len(strs)):
            char = strs[i]
            j = 0
            '''按順序從頭到尾判斷 如果第一位就不同 肯定不是'''
            while j < length and j < len(char) and char[j] == prefix[j]:
                j += 1
            '''修正需要判斷的長度'''
            length = j
        '''返回結果'''
        return prefix[:length]