Trie หรือ Prefix Tree เป็นโครงสร้างข้อมูลสำหรับจัดเก็บสตริง รองรับ insert, search, startsWith
การทำงาน
- แต่ละโหนดเป็น dictionary mapping ตัวอักษร → โหนดถัดไป
- เครื่องหมาย
#(หรือ key ใดก็ได้) ใช้ระบุจบคำ
ตัวอย่างการใช้งาน
trie = Trie()
trie.insert("apple")
trie.search("apple") # True
trie.search("app") # False
trie.startsWith("app") # True
trie.insert("app")
trie.search("app") # True
โค้ด
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node['#'] = True # end-of-word marker
def search(self, word):
node = self.root
for ch in word:
if ch not in node:
return False
node = node[ch]
return '#' in node
def startsWith(self, prefix):
node = self.root
for ch in prefix:
if ch not in node:
return False
node = node[ch]
return True
# ทดสอบ
trie = Trie()
trie.insert("apple")
print(trie.search("apple")) # True
print(trie.search("app")) # False
print(trie.startsWith("app")) # True
trie.insert("app")
print(trie.search("app")) # True
ความซับซ้อน
- Time: O(m) ต่อ operation (m = ความยาวสตริง)
- Space: O(ALPHABET_SIZE × N × M)
สรุป
Trie เหมาะสำหรับ autocomplete, spell checker, IP routing