【字典树】leetcode - Word Search II

题目:leetcode

Word Search II

 

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Return ["eat","oath"].

Note:
You may assume that all inputs are consist of lowercase letters a-z.


分析:

1、使用字典树。

2、用一个指针指向字典树的某个结点,代表字符串的某一位。这样在递归过程中,判断一个字符串在字典树中是否是前缀时,不用从字符串的开头开始遍历字典树。

3、标记某个位置是否被访问,用二维数组而不是哈希表。


class TrieNode {
public:
	// Initialize your data structure here.
	TrieNode() {
		isend = false;
		for (int i = 0; i<26; ++i)
		{
			child[i] = nullptr;
		}
	}
	bool isend;
	TrieNode* child[26];
};

class Trie {
public:
	Trie() {
		root = new TrieNode();
	}

	// Inserts a word into the trie.
	void insert(string s) {
		if (s.empty())
			return;
		int index = 0;
		TrieNode* cur = root;
		while (index<s.size())
		{
			int temp = s[index] - 'a';
			if (cur->child[temp] == nullptr)
				break;
			else
			{
				cur = cur->child[temp];
				++index;
			}
		}
		if (index == s.size())
		{
			cur->isend = true;
			return;
		}

		while (index<s.size())
		{
			int temp = s[index] - 'a';
			cur->child[temp] = new TrieNode();
			cur = cur->child[temp];
			++index;
		}
		cur->isend = true;
	}

    //返回的第二个参数是指向最后一个字母的指针
	pair<bool, TrieNode*> startsWith(string prefix) {
		if (prefix.empty())
			return make_pair(true, nullptr);
		int index = 0, temp = 0;
		TrieNode* cur = root;
		while (index<prefix.size())
		{
			temp = prefix[index] - 'a';
			if (cur->child[temp] == nullptr)
				return make_pair(false, nullptr);
			else
			{
				++index;
				cur = cur->child[temp];
			}
		}
		return make_pair(true, cur);
	}


	TrieNode* root;
};


class Solution {
public:

	Trie m_tree;

	vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
		vector<string> res;
		if (words.empty() || board.empty() || board[0].empty())
			return res;
		int rows = board.size(), cols = board[0].size();
		size_t sum = rows*cols;
		for (auto &word : words)
		{
			if (word.size() <= sum)
			{
				m_tree.insert(word);
			}
				
		}
        
        //注意,应该用二维数组标识某个位置是否已经被访问,用set的话花费时间过大
        vector<vector<bool>> visit(rows,vector<bool>(cols,false));
        //为了返回值没有重复,应该使用unordered_set
		unordered_set<string> result;
		for (int i = 0; i<board.size(); ++i)
		{
			for (int j = 0; j<board[0].size(); ++j)
			{
				char c = board[i][j];
				string str(1, c);
				auto p = m_tree.startsWith(str);
				if (p.first)
				{
					if (p.second->isend)
					{
						result.insert(str);
					}
				    visit[i][j]=true;
					findWords_core(board, i, j, p.second, result, visit, str);
					visit[i][j]=false;
				}
			}
		}
		for (auto &w : result)
			res.push_back(w);
		return res;
	}


	void findWords_core(vector<vector<char>>& board, int i, int j, TrieNode* root, unordered_set<string> &res,  vector<vector<bool>> &visit, string str)
	{
		int rows = board.size(), cols = board[0].size();
		if (i + 1<rows && visit[i+1][j]==false)
		{
			char c = board[i + 1][j];
		
			if (root->child[c - 'a'])
			{
				visit[i+1][j]=true;
				string tmp = str + string(1, c);
				if (root->child[c - 'a']->isend)
				{
					res.insert(tmp);
				}
				findWords_core(board, i + 1, j, root->child[c - 'a'], res, visit, tmp);
					visit[i+1][j]=false;
			}
			
		}
		if (i - 1 >= 0 && visit[i-1][j] == false)
		{
			char c = board[i - 1][j];
			
			if (root->child[c - 'a'])
			{
			    visit[i-1][j] =true;
				string tmp = str + string(1, c);
				if (root->child[c - 'a']->isend)
				{
					res.insert(tmp);
				}
				findWords_core(board, i - 1, j, root->child[c - 'a'], res, visit, tmp);
				visit[i-1][j] =false;
			}
			
		}
		if (j + 1<cols && visit[i][j+1]== false)
		{
			char c = board[i][j + 1];
			
			if (root->child[c - 'a'])
			{
				string tmp = str + string(1, c);
				visit[i][j+1]=true;
				if (root->child[c - 'a']->isend)
				{
					res.insert(tmp);
				}
				findWords_core(board, i, j + 1, root->child[c - 'a'], res, visit, tmp);
				visit[i][j+1]=false;
			}
			
		}
		if (j - 1 >= 0 && visit[i][j-1]==false)
		{
			char c = board[i][j - 1];
			if (root->child[c - 'a'])
			{
				string tmp = str + string(1, c);
			visit[i][j-1]=true;
				if (root->child[c - 'a']->isend)
				{
					res.insert(tmp);
				}
				findWords_core(board, i, j - 1, root->child[c - 'a'], res, visit, tmp);
				visit[i][j-1]=false;
			}
			
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值