首页 > 编程知识 正文

leetcode刷题速度,leetcode100题

时间:2023-05-03 07:10:10 阅读:53932 作者:1874

主题描述给定的m x n二维字符网格board和单词(字符串)列表words,找出二维网格和词典中同时出现的所有单词。 单词必须按字母顺序由相邻zzdwd中的字符组成。 其中“相邻”zzdwd是水平相邻的zzdwd或垂直相邻的zzdwd。 同一zzdwd中的字符不能在一个单词中重复使用。 例1 :输入: board=[['o '、' a '、' a '、' n']、['e '、' t '、' a '、' e']、['i '、' h '、' k '、' r ] words=['abcb']输出: []提示: m===board.lengthn n=12 board [ I ] [ j ]表示1=words.length=3* 1041=words [ 力挽(商业转载请联系官方授权。 非商业转载请注明出处。

想法

1、不同于单词搜索I处理的数据很多,不能用以前的方法简单地对每个单词进行深度搜索总结,超时

2、使用前缀树tria,将单词构建成trial树后进行处理

代码

打包管理端口(' fmt )//前缀树结构。 请注意,childres是地图。 这样,在o(1)时间内就可以找到孩子的节点typetriastruct (字符映射) string (triaiswordbool ) funcfindwords (板) ) byte。 words[]string][]string{//先构建tria树varroot=new(tria ) rootb :=root//遍历单词片for _, v:=rangewords(//root/遍历每个单词在构建tria时使用root=rootb//单词字符串,并在前缀树中for _, 2:=rangev { if root.childres [ string (v2 ) ]==nil(tmp:=new(tria ) ifroot.childres==nil ) root.chil root=root.childres[string(V2 ) ](/标记至此为单词root.isword=true ) /,开始处理true已经是log [ 12 ] [ 12 ] bolss 将贴图转换为切片以生成RES=make([]string,0 ) resm=make () map () string,0 ) resm () map ) Ilen(Board; i {for j:=0; Jlen(board[0]; j { ifrootb.childres [ string [ board [ I ] [ j ] ]!=nil { DFS (板、根、日志、I、j、str、resM ) }//转换为主题所需的切片类型for k, v:=rangeresM ) ifv==true{res=appes} true表示已经在使用,rowI和colI是矩阵的后缀,str是前缀字符串,resm是满足要求的单词func DFS (boares ) rowI int,resm * map [ string ] bool (var (row=len ) board (col=len ) (board(0) ) ) /递归终止条件为下标越界或使用递归if coli=col|||co li0|| rowi=row|||log [ rowi ] [ coli ]==true { return } /当前节点中不存在该字符,不符合要求验证递归if root.childres [字符串(* board ) rowi ) ) coli ]==nil { return }//是否满足要求, 将前缀树字符转换为字符串wordstr=string ) (boarrn ) )并保存在resM中的ifroot.childres[string(*board ) [ rowi ] [ coli ] ] ].is word=是该当前位置的上下左右位置DFS(board,root.childres [ string ] (board ) rowI 1) ],log,rowI 1,colI,str,resM ) DFS ) board,rowI 1 resm(DFS(board,root.Childres(string ) (*board ) [rowI][colI] ),log,rowI,root.childres [ string (* bow ) resM ) }func main ) { vartmp=tmp=[ ] byte (o )、(t )、(a )、(e ) ) t=append ) t,mp ) tmp=[]byte(a )

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。