c_cpp 特里
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 特里相关的知识,希望对你有一定的参考价值。
#pragma once
#include <string>
#include <map>
#include <queue>
typedef struct TrieNode {
bool completed;
std::map<char, TrieNode *> children;
TrieNode() : completed(false){};
} TrieNode;
class Trie{
public:
Trie();
~Trie();
void insert(std::string word);
bool search(std::string word);
private:
TrieNode *root;
};
#include <iostream>
#include <cstdlib>
#include "trie.h"
using namespace std;
Trie::Trie() {
root = new TrieNode();
}
Trie::~Trie() {
queue<TrieNode *> data;
data.push(root);
//BFS
while(!data.empty()){
TrieNode *curr = data.front();
data.pop();
for (auto iter = curr->children.begin(); iter != curr->children.end(); ++iter){
data.push(iter->second);
}
delete curr;
}
}
void Trie::insert(string word) {
TrieNode *curr = root;
for (int i = 0; i < word.size(); ++i) {
if(curr->children.find(word[i]) == curr->children.end())
curr->children[word[i]] = new TrieNode();
curr = curr->children[word[i]];
}
curr->completed = true;
}
bool Trie::search(string word) {
TrieNode *curr = root;
for (int i = 0; i < word.size(); ++i) {
if(curr->children.find(word[i]) == curr->children.end())
return false;
curr = curr->children[word[i]];
}
return curr->completed;
}
#include <iostream>
#include <cstdlib>
#include <memory>
#include "trie.h"
#include "../unit_test.h"
//execution flow:
//set up -> section1 -> tear down -> set up -> section2 -> tear down
// std::unique_ptr<Trie> t = std::make_unique<Trie>();
TEST_CASE("Testing Trie") {
//set up
// Trie *t = new Trie();
std::unique_ptr<Trie> t = std::make_unique<Trie>();
//different sections
SECTION("Search an existent word.") {
std::string word = "abandon";
t->insert(word);
REQUIRE(t->search(word) == true);
}
SECTION("Search a nonexistent word.") {
std::string word = "abadon";
REQUIRE(t->search(word) == false);
}
//tear down
std::cout << "tear down" << std::endl;
// delete t;
}
以上是关于c_cpp 特里的主要内容,如果未能解决你的问题,请参考以下文章
python 基本特里对象
韦塞特·泽特里伦
Android UI贝塞尔曲线 ⑤ ( 德卡斯特里奥算法 | 贝塞尔曲线递推公式 )
特里和子序列
最长回文子串和后缀特里树
《一只特里独行的猪》有感