题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param strs string字符串一维数组 # @return string字符串 # class Solution: def longestCommonPrefix(self , strs: List[str]) -> str: # write code here n = len(strs) if n == 0: return "" # 处理空数组 short = len(strs[0]) p = 0 for i in range(n): if len(strs[i]) < short: short = len(strs[i]) p = i # 找出最短的字符串并标记位置 for i in range(short): # 遍历最短的字符串,最长子串不会超过该字符串 bs = strs[p][i] # 从首字符开始比对 for j in range(n): if strs[j][i] != bs: # 遇到不相等的字符,说明之前的字符都匹配成功 return strs[p][:i] return strs[p]