2023年4月27日 星期四

4/27 每日一題( 回傳最長的公共前綴)

 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.

class Solution:
    def longestCommonPrefix(self, strs):
        res=[]
        for i in zip(*strs):
#使用*str表示使用zip()將ex列表的元素展開
#所以i代表了每個元素的字元tuple>>("f","f","f")...("w","w","g")
            if all(j == i[0] for j in i):
        #檢查i(tuple)裡面的每個字元是否和i[0]相等,
        #也就說是否每個字元相等,如果相等加入到res
                res.append(i[0])
            else:
                break
            #遇到不同時馬上跳出迴圈
        return "".join(res)

s=Solution()
strs = ["flower","flow","flight"]
strs2 = ["dog","racecar","car"]
strs3=[]
print(s.longestCommonPrefix(strs)) #"fl"
print(s.longestCommonPrefix(strs2)) #""
print(s.longestCommonPrefix(strs3)) #""
strs4=["cir","car"]
print(s.longestCommonPrefix(strs4)) #"c"
---------------------------
終端機
PS C:\Users\K\OneDrive\桌面\AUTOKI> python tr.py fl

c

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁