中级农民
- 积分
- 100
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-6-30
- 最后登录
- 1970-1-1
|
- class Solution {
- class TrieNode{
- String word;
- TrieNode[] next = new TrieNode[26];
-
- }
- public List<String> findWords(char[][] board, String[] words) {
- TrieNode root = buildTrie(words);
- List<String> retList = new ArrayList<>();
- for(int i = 0; i < board.length; i++){
- for(int j = 0; j < board[0].length; j++){
- DFS(board, i, j, root, retList,true);//horizontally
- DFS(board, i, j, root, retList,false);//vertically
- }
- }
- return retList;
- }
- private void DFS(char[][] board, int i, int j, TrieNode node, List<String> retList, boolean isHorizontally){
- if(i < 0 || i == board.length || j < 0 || j == board[0].length || board[i][j] == '*') return;
-
- char c = board[i][j];
- if(node.next[c-'a'] == null) return;
- node = node.next[c - 'a'];
- if(node.word != null){
- retList.add(node.word);// find one, add to result list
- node.word = null;// deDuplicate
- }
- board[i][j] = '*';
- if(isHorizontally){
- DFS(board, i, j + 1, node, retList);
- }else{
- DFS(board, i + 1, j, node, retList);
- }
- board[i][j] = c;
- }
- private TrieNode buildTrie(String[] words){
- TrieNode root = new TrieNode();
- for(String word : words){
- TrieNode p = root;
- for(char c : word.toCharArray()){
- if(p.next[c-'a'] == null) p.next[c-'a'] = new TrieNode();
- p = p.next[c-'a'];
- }
- p.word = word;
- }
- return root;
- }
- }
复制代码 经楼上兄弟提示又去LC上复习了一下Trie的使用方法,附上代码供大家参考。
|
|