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

来源:互联网 发布:seo关键词怎么分 编辑:程序博客网 时间:2024/05/21 15:45

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
原创粉丝点击