鱼C论坛

 找回密码
 立即注册
查看: 1566|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】14. Longest Common Prefix #Easy #Python

[复制链接]
发表于 2021-5-7 11:48:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Write a function to find the longest common prefix string amongst an array of strings.

  2. If there is no common prefix, return an empty string "".


  3. Example 1:

  4. Input: strs = ["flower","flow","flight"]
  5. Output: "fl"

  6. Example 2:

  7. Input: strs = ["dog","racecar","car"]
  8. Output: ""
  9. Explanation: There is no common prefix among the input strings.


  10. Constraints:

  11. 1 <= strs.length <= 200
  12. 0 <= strs[i].length <= 200
  13. strs[i] consists of only lower-case English letters.
复制代码


Python
  1. class Solution:
  2.     def longestCommonPrefix(self, strs: List[str]) -> str:
  3.         retval = strs[0]
  4.         for x in strs:
  5.             while retval:
  6.                 if x.startswith(retval):
  7.                     break
  8.                 else:
  9.                     i = len(retval) - 1
  10.                     retval = retval[:i]
  11.         return retval
复制代码


unknown.png

Screen_Shot_2021-05-06_at_11.15.28_PM.png

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-7 21:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表