Leetcode题目之求字符串列表的最大前缀子串

题目描述如下:

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

其是就是对于一个有多个字符串为元素的一个列表,要求这几个元素的最大前缀字符串:

我的初始想法很简单,就是遍历这个列表,其实这个最大前缀子串的求解也是层层递进的,初始先求出前两个元素的前缀子串,之后根据前面的结果,再去求解后面的最大前缀子串。

代码分为两大部分,第一部分是主函数,第二部分的函数是用来求两个字符串的最大前缀子串的。

#-*-coding:utf-8-*-
class Solution:
    def longestCommonPrefix(self, strs):
        #if length of list equals 0,return NULL
        print(strs,type(strs))
        if len(strs) == 0:
            return ""
        #if length of list equals 1,return the whole only string
        elif len (strs) == 1:
            return strs[0]
        else:
            for i in range(len(strs)-1):
                temp = strs[i]
                #if one of the strings is NULL,return NULL
                if temp == "":
                    return ""
                # first,compare the first two element strings in the list
                if i == 0:
                    res = self.firstmatch(temp, strs[i+1])
                #then, compare the remaining elements,use the prefix got
                #last step to continue the later copmution
                else:
                    res = self.firstmatch(res, strs[i+1])
                if res == "":
                    return ""
        return res
    #get the common prefix string of two strings
    def firstmatch(self,a,b):
        #the result is the finally output
        result = ""
        for i in range(len(a)):
            if (len(a) > len(b) and i >= len(b)) or a[i] != b[i]:
                break
            if (len(a) < len(b) and i >= len(a)) or a[i] != b[i]:
                break
            result +=a[i]
        return result
if __name__ == '__main__':
    Prelist = input("input a list:")
    # obj = list(Prelist.split(","))
    # print(obj)
    list(Prelist)
    # print(Prelist)
    # print(type(Prelist))
    Prelist = list(Prelist.split("["))
    # print(Prelist)
    Prelist = Prelist[1]
    # print(Prelist)
    Prelist = list(Prelist.split("]"))
    # print(Prelist)
    Prelist = Prelist[0]
    # print(Prelist)
    # print(type(Prelist))
    Prelist = list(Prelist.split(","))
    # print(Prelist)
    # print(type(Prelist))
    for i in range(len(Prelist)):
        Prelist[i] = Prelist[i][1:-1]
    # print(Prelist)
    # print(Prelist.split("["))

    S = Solution()
    print(S.longestCommonPrefix(Prelist))

最后运行结果如下图:

Leetcode题目之求字符串列表的最大前缀子串_第1张图片

Leetcode题目之求字符串列表的最大前缀子串_第2张图片

最后如果没有,则输出为空,其实可以修改下输出来提示最大前缀子串为空的,这里就不赘述。

2018.12.10 晚23:42

你可能感兴趣的:(python算法)