題目:Write a function to find the longest common PRefix string amongst an array of strings.
思路:找出最小長(zhǎng)度的字符串,逐個(gè)子集判斷,判斷時(shí)可以使用set,最后判斷set元素是否為1個(gè)即可。
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs)==0:return '' ind=0;minLen=len(strs[0]) for i in range(len(strs)): if len(strs[i])<minLen: ind = i;minLen=len(strs[i]) r = '' for i in range(minLen): s = set() for j in strs: s.add(j[:i+1]) if len(s)>1:return r r = s.pop() del s return r
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注