作者DJYOSHITAKA (franchouchouISBEST)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Tue Sep 24 23:35:46 2024
就用trie
不過速度很慢 不知道又怎麼了
板友 救救字典樹
class Node:
def __init__(self):
self.child = [None for _ in range(10)]
class Solution:
def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
# build trie for arr1
root = Node()
for num in arr1:
s = str(num)
cur = root
for c in s:
if cur.child[ord(c)-ord('0')] is None:
cur.child[ord(c)-ord('0')] = Node()
cur = cur.child[ord(c)-ord('0')]
# inference
ans = 0
for num in arr2:
s = str(num)
cur, cur_len = root, 0
for c in s:
if cur.child[ord(c)-ord('0')] is not None:
cur_len += 1
cur = cur.child[ord(c)-ord('0')]
else:
break
ans = max(ans, cur_len)
return ans
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.229.37.69 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1727192148.A.8F2.html
推 deatheo: 大師 09/24 23:40
→ sixB: 看起來跟我的沒兩樣 我的也好慢 09/24 23:41