#include <unordered_map>
#include <vector>
#include <memory>
#include <unordered_set>
#include <string_view>
#include <string>
#include <optional>
class trie{
struct Node;
using hasher
= std::unordered_map< char,
std::unique_ptr< Node > >;
struct Node{
std::optional< std::size_t > frequency { std::nullopt };
hasher children;
Node operator=( const Node& ) = delete;
};
private:
Node *root { nullptr };
Node *searchPrefix( const std::string_view& word ) const{
Node *ptr { root };
for( const auto& c : word ){
if( ! ptr->children.count( c ) )
return nullptr;
ptr = ptr->children[c].get();
}
return ptr;
}
public:
trie( void ) : root( new Node ) { }
trie operator=( const trie& ) = delete;
trie( trie&& other ) noexcept = default;
trie operator=( trie&& ) = delete;
~trie( void ) { if( root ) delete root; root = nullptr; }
void insert( const std::string_view& word ){
Node *ptr { root };
for( const auto& c : word ){
if( ! ptr->children.count( c ) )
ptr->children[c] = std::make_unique< Node >();
ptr = ptr->children[c].get();
}
if( ptr->frequency ) ptr->frequency = 1;
else ++*(ptr->frequency);
}
bool search( const std::string_view& word ) const{
Node *ptr { searchPrefix( word ) };
return static_cast< bool >( ptr && ptr->frequency );
}
std::size_t count( const std::string_view& word ) const{
return searchPrefix( word )->frequency.value_or( 0 );
}
bool startsWith( const std::string_view& word ) const{
return static_cast< bool >( searchPrefix( word ) );
}
};
【trie 字典树】( RAII | Multiset频次统计 | STL )
最新推荐文章于 2024-09-11 22:48:33 发布