leetcode208. Implement Trie (Prefix Tree)

题目:题目链接

Trie又称字典树,前缀树。具体性质可以参照英文官方题解,里面还有Trie的用法,可以去看看还是挺有意思的。
其实坦白来说就是建树,每棵树都有最多26个结点也就是26个英文字母,我的代码是按照中文官方题解写的,顺便加了点自己的理解。看代码吧:

class Trie {
private:
	vector<Trie*> children;//这是他的儿子,也是一棵Trie树
	bool isEnd;//该结点是否是叶子结点

	Trie* searchPrefix(string prefix) {
		Trie* node = this;//this指针这里可以理解为根结点
		for (char ch : prefix) {
			ch -= 'a';
			if (node->children[ch] == nullptr) return nullptr;//没有就别找了
			node = node->children[ch];//接着找下一个字符
		}
		return node;//全部找完了,就返回叶子结点
	}
public:
	Trie() : children(26), isEnd(false) {}

	void insert(string word) {//Inserts the string word into the trie.
		Trie* node = this;
		for (char ch : word) {
			ch -= 'a';
			if (node->children[ch] == nullptr) {//没有这个结点就创一个
				node->children[ch] = new Trie();
			}
			node = node->children[ch];
		}
		node->isEnd = true;//表示叶子结点,也就是说word已经在这棵树里面了
	}

	bool search(string word) {//Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
		Trie* node = this->searchPrefix(word);
		return node != nullptr && node->isEnd;
	}

	bool startsWith(string prefix) {//Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
		return this->searchPrefix(prefix) != nullptr;
	}
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

学习到了this指针的用法。
加油加油加油加油!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值