标签:import class pat 字符串 返回 sel span 最长公共前缀 pytho
第一轮刷题解法:
1)如果长度为1,返回第一个字符串;如果存在空,返回空;否则长度递增,逐一比较,有不同则返回当前前缀。
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: count_prefix = 1 if len(strs) == 1: return strs[0] if ‘‘ in strs: return ‘‘ while count_prefix <= len(strs[0]): temp = strs[0][0:count_prefix] for i in range(1,len(strs)): if strs[i][0:count_prefix] != temp: if count_prefix == 1: return ‘‘ else: return strs[0][0:count_prefix-1] count_prefix +=1 return strs[0][0:count_prefix-1]
2)开挂,os库寻找公共前缀
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: import os return os.path.commonprefix(strs)
标签:import class pat 字符串 返回 sel span 最长公共前缀 pytho
原文地址:https://www.cnblogs.com/cbachen/p/14832328.html