zoukankan      html  css  js  c++  java
  • LeetCode 14. Longest Common Prefix

    最长公共前缀

    看起来很简单 >,>

    first submission
    class Solution:
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            logestPrefix=''
            lenList=[len(s) for s in strs]
            mixLen=min(lenList)
    
            strLen=len(strs)
    
            for i in range(mixLen):
                cList=[s[i] for s in strs]
                if cList.count(cList[0])==strLen:
                    logestPrefix+=cList[0]
    
            return logestPrefix
    

    Runtime Error

    Runtime Error Message:
    Line 9: ValueError: min() arg is an empty sequence
    Last executed input:
    []
    

    Wrong Answer

    Input:
    ["aca","cba"]
    Output:
    "a"
    Expected:
    ""
    

    一是lenList为空不能用min()函数,
    二是遇到不相同则break

    小改之后AC

    完整代码
    import time
    
    class Solution:
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            logestPrefix=''
            lenList=[len(s) for s in strs]
            
            mixLen=min(lenList) if len(lenList)>0 else 0  
    
            strLen=len(strs)
    
            for i in range(mixLen):
                cList=[s[i] for s in strs]
                if cList.count(cList[0])==strLen:
                    logestPrefix+=cList[0]
                else:
                    break
    
            return logestPrefix
    
    if __name__ == "__main__":
        
        data = [
            {
                "input":["flower","flow","flight"],
                "output":"fl"
            },
            {
                "input":["dog","racecar","car"],
                "output":""
            },
            {
                "input":[],
                "output":""
            },
            {
                "input":["aca","cba"],
                "output":""
            }
     
        ];
        for d in data:
            
            print(d['input'])
            
            # 计算运行时间
            start = time.perf_counter()
            result=Solution().longestCommonPrefix(d['input'])
            end = time.perf_counter()
            
            print(result)
            if result==d['output']:
                print("--- ok ---> spend time: ",end-start)
            else:
                print("--- error ---> spend time: ",end-start)
                break
            
            print()
        else:
            print("success")
    
  • 相关阅读:
    oracleI基础入门(6)sql语句Substring Crazy
    oracleI基础入门(7)table约束 Crazy
    oracleI基础入门(7)table视图 Crazy
    SQL附加分离数据库(命令)
    双截棍 C语言版 (超搞笑)
    AspNetPage分页(repeater),自己做的例子基本代码
    记录
    RegularExpressionValidator控件中正则表达式用法
    20 个经典的 Ajax + CSS 表格
    GridView各个事件中,怎样获取主键值
  • 原文地址:https://www.cnblogs.com/warcraft/p/9390338.html
Copyright © 2011-2022 走看看