[Leetcode] 14. Longest Common Prefix

2024/01/10閱讀時間約 2 分鐘

題目 : 14. Longest Common Prefix

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

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


Example 1:

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

Example 2:

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


1.


class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
#建立空的ans字串存重複的字母
ans = ""
# 先將字串集做排序
strs = sorted(strs)
# 比對第一個字串(shortest)和最後一個字串(longest)
first = strs[0]
last = strs[-1]
#用for迴圈逐一比對
for i in range(min(len(first),len(last))):
if (first[i]!=last[i]):
return ans
ans = ans + first[i]
return ans










7會員
36內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!