leetcode: string hard系列一:word search

本文介绍了一种使用字典树(Trie)结合深度优先搜索(DFS)算法来解决LeetCode上的单词搜索II问题的方法。通过对给定的单词列表构建字典树,并在二维矩阵中寻找这些单词,该算法能有效地找出所有匹配的单词。

https://leetcode.com/problems/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"].



首先是我最擅长的递归(DFS):

class Solution {
public:
    /************************************************************************/
	/*在一个二维字符矩阵里面找到相邻元素能够拼接成word*/
	/************************************************************************/
	vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
		vector<string>res;
		unordered_set<string>cache;
		for (auto x:words)
		{
			if (cache.find(x) == cache.end())
			{
				cache.insert(x);
				if (findAWord(board, x))
					res.push_back(x);
			}
			
		}
		return res;
	}
	bool findAWord(const vector<vector<char>>& board, string s)
	{
		//考虑每个s[i]可能在多个位置上出现
		//用递归
		int n = board.size();
		int m = board[0].size();
		vector<vector<bool>>used(n, vector<bool>(m, false));
		for (int i=0;i<n;++i)
		{
			for (int j=0;j<m;++j)
			{
				if (board[i][j] == s[0])
				{
					used[i][j] = true;
					if (__findAWords(board, used,i,j, s.substr(1)))return true;
					used[i][j] = false;
				}
			}
		}
		return false;
	}
	bool __findAWords(const vector<vector<char>>& board, vector<vector<bool>>&used, int x, int y, string s)
	{
		if (s.size() == 0)return true;
		//上下左右四个方向的检测
		if (x > 0)//shang
		{
			if (used[x - 1][y] == false && board[x - 1][y] == s[0])
			{
				used[x - 1][y] = true;
				if (__findAWords(board, used, x-1, y, s.substr(1)))return true;
				used[x - 1][y] = false;
			}
		}
		if (x < board.size()-1)//下
		{
			if (used[x + 1][y] == false && board[x + 1][y] == s[0])
			{
				used[x + 1][y] = true;
				if (__findAWords(board, used, x + 1, y, s.substr(1)))return true;
				used[x + 1][y] = false;
			}
		}
		if (y > 0)//左
		{
			if (used[x][y-1] == false && board[x][y-1] == s[0])
			{
				used[x][y-1] = true;
				if (__findAWords(board, used, x, y-1, s.substr(1)))return true;
				used[x][y-1] = false;
			}
		}
		if (y < board[0].size()-1)//右
		{
			if (used[x][y+1] == false && board[x][y+1] == s[0])
			{
				used[x][y+1] = true;
				if (__findAWords(board, used, x, y+1, s.substr(1)))return true;
				used[x][y+1] = false;
			}
		}
		return false;
	}
};
有三个函数组成

第一个遍历words所有的word,对每一个word进行查找

第二个,查找函数,传递used数组,标记board的使用

第三个,递归函数, 截止条件,上下左右的查找

幸运的是:这种做法能够把word search I里面的AC

遗憾的是:Time Limit Exceeded

此版本的改进版:

public boolean exist(char[][] board, String word) {
    char[] w = word.toCharArray();
    for (int y=0; y<board.length; y++) {
    	for (int x=0; x<board[y].length; x++) {
    		if (exist(board, y, x, w, 0)) return true;
    	}
    }
    return false;
}

private boolean exist(char[][] board, int y, int x, char[] word, int i) {
	if (i == word.length) return true;
	if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
	if (board[y][x] != word[i]) return false;
	board[y][x] ^= 256;
	boolean exist = exist(board, y, x+1, word, i+1)
		|| exist(board, y, x-1, word, i+1)
		|| exist(board, y+1, x, word, i+1)
		|| exist(board, y-1, x, word, i+1);
	board[y][x] ^= 256;
	return exist;
}
改进的地方在于:

1. 使用mask代替了used标记数组,巧妙

2. 递归开始的和截止地方有些差异,这种改进更清晰,明显缩短代码量

解决word search II

使用tries字典树对words进行预处理,然后dfs


struct TrieNode
{
	//只有小写字母
	TrieNode* next[26];
	string nodecontent;
	TrieNode() 
	{
        <span style="white-space:pre">	</span>for(int i=0;i<26;i++)next[i]=nullptr;  //初始全部为NULL
		nodecontent = string("");  //赋值空
	}
};

//有很多string 构造成的root node

TrieNode* getTrieroot(const vector<string>&vs)
{
	TrieNode* root=new TrieNode();
	for (string x:vs)  //注意此处的技巧,遍历所有的string
	{
		TrieNode* p = root;
		for (char c:x)
		{
			int i = c - 'a'; //所有char都是小写字母
			if (p->next[i]==NULL)  //在字典树中,每个节点可能有26个可能,只适合此题的情况
			{
				p->next[i] = new TrieNode();
			}
			p = p->next[i];  //对一个string全部遍历完
		}
		p->nodecontent = x;  //最后的node存储这个string
	}
	return root;
}

class Solution
{
public:
	/************************************************************************/
	/*在一个二维字符矩阵里面找到相邻元素能够拼接成word*/
	//使用 tries字典树和dfs
	/************************************************************************/
	vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
		vector<string>res;
		TrieNode* root = getTrieroot(words);  //转为字典树
		for (int i=0;i<board.size();++i)
		{
			for (int j=0;j<board[0].size();++j)
			{
				findWordsDFS(board, i, j, root, res);  //对每一个位置,DFS
			}
		}
		return res;
	}
	void findWordsDFS(vector<vector<char>>& board, int i, int j, TrieNode* root, vector<string>&res)
	{
		char c = board[i][j];
		if (c == '#' || root->next[c - 'a'] == NULL)return; //赋值为'#'表示当前节点已经访问过了了
		root = root->next[c - 'a']; //当前节点不存储,指向下一个节点
		if (root->nodecontent.size()!=0)
		{
			res.push_back(root->nodecontent);
			root->nodecontent.clear(); //去重,既然这个string已经找到了,那就在字典树里面删除它,防止board其它路劲也可以找到这个string
		}
		board[i][j] = '#';//当前这个位置已经访问了
		if (j > 0)findWordsDFS(board, i, j - 1, root, res);
		if (i > 0)findWordsDFS(board, i - 1, j, root, res);
		if (j < board[0].size() - 1)findWordsDFS(board, i, j + 1, root, res);
		if (i < board.size() - 1)findWordsDFS(board, i + 1, j, root, res);
		board[i][j] = c;
	}
private:
};
巧妙地利用了字典树,遍历二维board里面的每个点的时候,对所有的需要匹配的word信息进行了关联,而不用想当个word那种一个个单次匹配。



(1)普通用户端(全平台) 音乐播放核心体验: 个性化首页:基于 “听歌历史 + 收藏偏好” 展示 “推荐歌单(每日 30 首)、新歌速递、相似曲风推荐”,支持按 “场景(通勤 / 学习 / 运动)” 切换推荐维度。 播放页功能:支持 “无损音质切换、倍速播放(0.5x-2.0x)、定时关闭、歌词逐句滚动”,提供 “沉浸式全屏模式”(隐藏冗余控件,突出歌词与专辑封面)。 多端同步:自动同步 “播放进度、收藏列表、歌单” 至所有登录设备(如手机暂停后,电脑端打开可继续播放)。 音乐发现与管理: 智能搜索:支持 “歌曲名 / 歌手 / 歌词片段” 搜索,提供 “模糊匹配(如输入‘晴天’联想‘周杰伦 - 晴天’)、热门搜索词推荐”,结果按 “热度 / 匹配度” 排序。 歌单管理:创建 “公开 / 私有 / 加密” 歌单,支持 “批量添加歌曲、拖拽排序、键分享到社交平台”,系统自动生成 “歌单封面(基于歌曲风格配色)”。 音乐分类浏览:按 “曲风(流行 / 摇滚 / 古典)、语言(国语 / 英语 / 日语)、年代(80 后经典 / 2023 新歌)” 分层浏览,每个分类页展示 “TOP50 榜单”。 社交互动功能: 动态广场:查看 “关注的用户 / 音乐人发布的动态(如‘分享新歌感受’)、好友正在听的歌曲”,支持 “点赞 / 评论 / 转发”,可直接点击动态中的歌曲播放。 听歌排行:个人页展示 “本周听歌 TOP10、累计听歌时长”,平台定期生成 “全球 / 好友榜”(如 “好友中你本周听歌时长排名第 3”)。 音乐圈:加入 “特定曲风圈子(如‘古典音乐爱好者’)”,参与 “话题讨论(如‘你心中最经典的钢琴曲’)、线上歌单共创”。 (2)音乐人端(创作者中心) 作品管理: 音乐上传:支持 “无损音频(FLAC/WAV)+ 歌词文件(LRC)+ 专辑封面” 上传,填写 “歌曲信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值