給定 10,000 張含英文單字的圖片,其中單一單字重複出現兩次,需快速找出該重複單字。核心流程分兩階段:
建立 26 叉樹,每個節點含 children[26] 指標與 bool isEnd 標記。插入單字時,若走訪到終端節點 isEnd == true,即發現重複。
struct TrieNode {
TrieNode* children[26] = {nullptr};
bool isEnd = false;
};
bool insertAndCheck(TrieNode* root, const string& word) {
TrieNode* p = root;
for (char ch : word) {
int idx = tolower(ch) - 'a';
if (idx < 0 || idx >= 26) continue; // 忽略非字母
if (!p->children[idx]) p->children[idx] = new TrieNode();
p = p->children[idx];
}
if (p->isEnd) return true; // 重複
p->isEnd = true;
return false;
}
unordered_set<string>,代碼最簡潔,效能同級。sort 後掃描相鄰重複,無額外資料結構開銷。生產環境建議:OCR 階段使用多進程/分散式佇列(Celery/RQ)並行;去重階段用 unordered_set 開發最快,若記憶體極限才考慮字典樹或外部排序。