[LeetCode][Python]14: Longest Common Prefix

# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'
https://oj.leetcode.com/problems/longest-common-prefix/
14: Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.
===Comments by Dabay===
注意边界条件,如果strs为空,直接返回空字符串。

初始化共同前缀为空字符串。
如果一个字符出现在每个字符的相应位置就把这个字符加到共同前缀中。
'''

class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ""
common_pre = ""
i = 0
while True:
to_compare = ""
for s in strs:
if i >= len(s):
return common_pre
if to_compare == "":
to_compare = s[i]
continue
if s[i] != to_compare:
return common_pre
else:
common_pre = common_pre + to_compare
i = i + 1


def main():
s = Solution()
strs = ["abcdef", "abc", "abcd"]
print s.longestCommonPrefix(strs)


if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)


转载于:https://www.cnblogs.com/Dabay/p/4234693.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值