(LeetCode)Longest Common Prefix --- 最长公共前缀

来源:互联网 发布:企业群发短信软件 编辑:程序博客网 时间:2024/05/17 05:52

Write a function to find the longest common prefix string amongst an array of strings.

Subscribe to see which companies asked this question


解题分析:

首先要理解,如果是空串的话,那么说明前缀就是 “”

如果都是以 " "开头的,那么就是“ ”

然后最长的前缀不会超过最短的字串的距离,那么可以遍历最短的字串的长度,依次比较。

# -*- coding:utf-8 -*-__author__ = 'yx'class Solution(object):    def longestCommonPrefix(self, strs):        if len(strs) == 0:            return ""        for i in range(1, len(strs)):            l1 = len(strs[0])            l2 = len(strs[i])            if l1 > l2:                length = l2            else:                length = l1            if length == 0:                return ""            strs[0] = strs[0][0:length]            for j in range(length):                if strs[0][j] != strs[i][j]:                    strs[0] = strs[0][0:j]                    break        return strs[0]


0 0