zoukankan      html  css  js  c++  java
  • [leetcode]14. Longest Common Prefix

    方法有点蠢,没想好怎么不用循环取所有元素的前index位,就顺手这么写了。

    Success
    Details 
    Runtime: 32 ms, faster than 99.37% of Python3 online submissions forLongest Common Prefix.
    Memory Usage: 13.2 MB, less than 36.85% of Python3 online submissions for Longest Common Prefix.
     

    Submission Detail

    118 / 118 test cases passed.
    Status: 

    Accepted

    Runtime: 32 ms
    Memory Usage: 13.2 MB
    Submitted: 2 minutes ago
    class Solution:
        def longestCommonPrefix(self, strs: List[str]) -> str:
            times = 0
            for index in range(len(strs)):
                if len(strs[index]) > times:
                    times = len(strs[index])
            #circle for (times) times
            ret =''
            for index in range(times):
                isequal = True
                temp = strs[0][:index+1]
                for i in range(1,len(strs)):
                    if temp == strs[i][:index+1]:
                        pass
                    else:
                        isequal = False
                        break
                if isequal:
                    ret = temp
                else:
                    break
            return ret

    国际惯例抄一个:

    class Solution:
        def longestCommonPrefix(self, strs: List[str]) -> str:
            if '' in strs or not strs:  return ''
            index = 0
            for i, item in enumerate(zip(*strs)):
                if len(set(item)) != 1:
                    return strs[0][:i]
                else:  index = i
            return strs[0][:index + 1]
  • 相关阅读:
    sublime text添加snippet
    python __globals__, __file__
    Zen of Python
    Python的魔法函数之
    tornado session
    sqlalchemy学习
    自控力
    无需编译、快速生成 Vue 风格的文档网站
    python描述符理解
    python property理解
  • 原文地址:https://www.cnblogs.com/alfredsun/p/10885507.html
Copyright © 2011-2022 走看看