Re: [閒聊] 每日leetcode

作者: dont   2024-09-24 23:26:02
3043. Find the Length of the Longest Common Prefix
## 思路
先對arr1建TrieTree, 再查找arr2的字在TrieTree裡的LCP
## Code
```python
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class TrieTree:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
curr = self.root
for ch in word:
if ch not in curr.children:
curr.children[ch] = TrieNode()
curr = curr.children[ch]
curr.is_word = True
def search(self, word):
res = 0
curr = self.root
for ch in word:
if ch not in curr.children:
break
curr = curr.children[ch]
res += 1
return res
class Solution:
def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
trie = TrieTree()
for num in arr1:
trie.insert(str(num))
res = 0
for num in arr2:
res = max(res, trie.search(str(num)))
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com