【trie 字典树】( RAII | Multiset频次统计 | STL )

#include 
#include 
#include 
#include 
#include 
#include 
#include 

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 ) );
	}
};

你可能感兴趣的:(ADT数据结构实现,语言特性,Modern,Cpp,算法,数据结构,c++,stl,hash,链表)