leetcode 212: Word Search II使用前缀树,java实现

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. 题目分析

看到题目,首先想到的是需要使用DFS递归的查找字符串,但是问题来了,什么时候该结束递归呢?当发现当前字符串继续往下递归也不可能是我们要找的字符串中的任意一个的时候。那么,这个时候我们就想到了使用前缀树,当发现当前字符串不是要找任何字符串的前缀的时候,就可以结束搜索。这样可以大大降低搜索的复杂度。关于前缀树的介绍可以参考我上一篇博客。

2. 代码实现

前缀树搜索算法
public class WordSearch2 {
	//使用set存储,为了避免board中重复字母导致重复的词
	Set<String> res=new HashSet<String>();
    public List<String> findWords(char[][] board, String[] words) {
    	//为了快速地检索单词,我们使用前缀树
    	Trie trie=new Trie();
    	for(String w:words)
    	{
    		trie.insert(w);
    	}
    	int m=board.length;
    	if(m<1) return new ArrayList<String>(res);
    	int n=board[0].length;
    	boolean[][] visited=new boolean[m][n];
    	for(int i=0;i<m;i++)
    	{
    		for(int j=0;j<n;j++)
    		{
    			findWords(board,visited,"",i,j,trie);
    		}
    	}
       
    	return new ArrayList<String>(res);
    }
    /**递归的查找单词*/
    public void findWords(char[][] board,boolean[][] visited,String str,int x,int y ,Trie trie)
    {
    	if(x<0||x>=board.length||y<0||y>=board[0].length)
    		return;
    	if(visited[x][y]) return;
    	String newstr=str+board[x][y];
    	if(!trie.startsWith(newstr))
    		return;
    	if(trie.search(newstr))
    	{
    		res.add(newstr);
    	}
    	visited[x][y]=true;
    	findWords(board,visited,newstr,x-1,y,trie);
    	findWords(board,visited,newstr,x+1,y,trie);
    	findWords(board,visited,newstr,x,y-1,trie);
    	findWords(board,visited,newstr,x,y+1,trie);
    	visited[x][y]=false;//注意回溯
    }
    
}

前缀树Trie源代码:
class TrieNode {
	//存储子节点
	TrieNode[]  children=new TrieNode[26];
	//存储一条记录,即对应一个单词
	String item="";
    // Initialize your data structure here.
    public TrieNode() {
        
    }
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
       TrieNode node=this.root;
       for(char c:word.toCharArray())
       {
    	   if(node.children[c-'a']==null)
    	   {
    		   node.children[c-'a']=new TrieNode();
    	   }
    	   node=node.children[c-'a'];
       }
       node.item=word;
        
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
    	TrieNode node=this.root;
        for(char c:word.toCharArray())
        {
     	   if(node.children[c-'a']==null)
     	   {
     		   return false;
     	   }
     	   node=node.children[c-'a'];
        }
        //注意需要判断搜索截止位置是前缀还是一个单词
        return node.item.equals(word);
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
    	TrieNode node=this.root;
        for(char c:prefix.toCharArray())
        {
     	   if(node.children[c-'a']==null)
     	   {
     		   return false;
     	   }
     	   node=node.children[c-'a'];
        }
        return true;
    }

}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值