Advertisement
lifeiteng

425. Word Squares

Sep 13th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. class Solution {
  2.     public List<List<String>> wordSquares(String[] words) {
  3.         if(words == null || words.length < 1) return re;
  4.         int n = words[0].length();
  5.         for(String w : words) root.insert(w);
  6.         dfs(words, new ArrayList<>());
  7.         return re;
  8.     }
  9.    
  10.     Trie root = new Trie();
  11.     List<List<String>> re = new ArrayList<>();
  12.    
  13.     void dfs(String[] words, List<String> list)
  14.     {
  15.         // System.out.println(list);
  16.         int n = words[0].length(), pos = list.size();
  17.         if(pos == n)
  18.         {
  19.             re.add(new ArrayList<>(list));
  20.             return;
  21.         }
  22.         if(pos >= words[0].length()) return;
  23.         String prefix = prefix(list);
  24.         Set<String> wordSet = root.getWords(prefix);
  25.         for(String word : wordSet)
  26.         {
  27.             list.add(word);
  28.             dfs(words, list);
  29.             list.remove(pos);
  30.         }
  31.     }
  32.    
  33.     String prefix(List<String> list)
  34.     {
  35.         int pos = list.size();
  36.         if(pos == 0) return "";
  37.         StringBuilder sb = new StringBuilder();
  38.         for(int i = 0; i < pos; i++) sb.append(list.get(i).charAt(pos));
  39.         return sb.toString();
  40.     }
  41.  
  42.     class Trie
  43.     {
  44.         Trie[] child = new Trie[26];
  45.         Set<String> set = new HashSet<>();
  46.        
  47.         void insert(String str)
  48.         {
  49.             Trie root = this;
  50.             for(char ch : str.toCharArray())
  51.             {
  52.                 root.set.add(str);
  53.                 if(root.child[ch - 'a'] == null) root.child[ch - 'a'] = new Trie();
  54.                 root = root.child[ch - 'a'];
  55.             }
  56.             root.set.add(str);
  57.         }
  58.        
  59.         Set<String> getWords(String prefix)
  60.         {
  61.             Trie root = this;
  62.             for(char ch : prefix.toCharArray())
  63.             {
  64.                 if(root.child[ch - 'a'] == null) return new HashSet<>();
  65.                 root = root.child[ch - 'a'];
  66.             }
  67.             return root.set;
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement