Given a set of words (without duplicates), find all word squares you can build from them.

A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).

For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.

b a l l
a r e a
l e a d
l a d y
Note:
There are at least 1 and at most 1000 words.
All words will have the exact same length.
Word length is at least 1 and at most 5.
Each word contains only lowercase English alphabet a-z.
Example 1: Input:
["area","lead","wall","lady","ball"] Output:
[
[ "wall",
"area",
"lead",
"lady"
],
[ "ball",
"area",
"lead",
"lady"
]
] Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
Example 2: Input:
["abat","baba","atan","atal"] Output:
[
[ "baba",
"abat",
"baba",
"atan"
],
[ "baba",
"abat",
"baba",
"atal"
]
] Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).

Backtracking + Trie:    referred to https://discuss.leetcode.com/topic/63516/explained-my-java-solution-using-trie-126ms-16-16

A better approach is to check the validity of the word square while we build it.
Example: ["area","lead","wall","lady","ball"]
We know that the sequence contains 4 words because the length of each word is 4.
Every word can be the first word of the sequence, let's take "wall" for example.
Which word could be the second word? Must be a word start with "a" (therefore "area"), because it has to match the second letter of word "wall".
Which word could be the third word? Must be a word start with "le" (therefore "lead"), because it has to match the third letter of word "wall" and the third letter of word "area".
What about the last word? Must be a word start with "lad" (therefore "lady"). For the same reason above.

The picture below shows how the prefix are matched while building the sequence.

In order for this to work, we need to fast retrieve all the words with a given prefix. There could be 2 ways doing this:

  1. Using a hashtable, key is prefix, value is a list of words with that prefix.
  2. Trie, we store a list of words with the prefix on each trie node.

The implemented below uses Trie.

 public class Solution {
public class TrieNode {
TrieNode[] sons;
List<String> startWith;
public TrieNode() {
this.sons = new TrieNode[26];
this.startWith = new ArrayList();
}
} public class Trie {
TrieNode root;
public Trie() {
this.root = new TrieNode();
} public void insert(String word) {
char[] arr = word.toCharArray();
TrieNode node = root;
for (char c : arr) {
if (node.sons[(int)(c-'a')] == null) {
node.sons[(int)(c-'a')] = new TrieNode();
}
node.sons[(int)(c-'a')].startWith.add(word);
node = node.sons[(int)(c-'a')];
}
} public List<String> findByPrefix(String prefix) {
char[] pre = prefix.toCharArray();
TrieNode node = root;
for (char c : pre) {
if (node.sons[(int)(c-'a')] == null) {
return new ArrayList<String>();
}
node = node.sons[(int)(c-'a')];
}
return node.startWith;
}
} public List<List<String>> wordSquares(String[] words) {
List<List<String>> res = new ArrayList<>();
if (words==null || words.length==0) return res;
int len = words[0].length(); //build trie
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
} List<String> path = new ArrayList<String>();
for (String word : words) {
path.add(word);
helper(res, path, trie, len);
path.remove(path.size()-1);
}
return res;
} public void helper(List<List<String>> res, List<String> path, Trie trie, int len) {
if (path.size() == len) {
res.add(new ArrayList<String>(path));
return;
}
int pos = path.size();
StringBuilder prefix = new StringBuilder();
for (String str : path) {
prefix.append(str.charAt(pos));
}
List<String> nextPossible = trie.findByPrefix(prefix.toString());
for (String str : nextPossible) {
path.add(str);
helper(res, path, trie, len);
path.remove(path.size()-1);
}
}
}

Leetcode: Word Squares && Summary: Another Important Implementation of Trie(Retrieve all the words with a given Prefix)的更多相关文章

  1. [LeetCode] Word Squares 单词平方

    Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...

  2. LeetCode:Word Ladder I II

    其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...

  3. LeetCode Monotone Stack Summary 单调栈小结

    话说博主在写Max Chunks To Make Sorted II这篇帖子的解法四时,写到使用单调栈Monotone Stack的解法时,突然脑中触电一般,想起了之前曾经在此贴LeetCode Al ...

  4. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  5. [Lintcode]Word Squares(DFS|字符串)

    题意 略 分析 0.如果直接暴力1000^5会TLE,因此考虑剪枝 1.如果当前需要插入第i个单词,其剪枝如下 1.1 其前缀(0~i-1)已经知道,必定在前缀对应的集合中找 – 第一个词填了ball ...

  6. Word Squares

    Description Given a set of words without duplicates, find all word squares you can build from them. ...

  7. LC 425. Word Squares 【lock,hard】

    Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...

  8. 【LeetCode】228. Summary Ranges 解题报告(Python)

    [LeetCode]228. Summary Ranges 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/sum ...

  9. Leetcode: LFU Cache && Summary of various Sets: HashSet, TreeSet, LinkedHashSet

    Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the f ...

随机推荐

  1. BestCoder Round #86

    A题 Price List 巨水..........水的不敢相信. #include <cstdio> typedef long long LL; int main() { int T; ...

  2. featherview模板引擎

    1.判断语法 <?php if(isset($value['fromVR']) && !empty($value['fromVR'])) {?> <s class=& ...

  3. node.js安装

    Node.js是一个基于Chrome JavaScript运行时建立的一个平台,用来方便地搭建快速的,易于扩展的网络应用Node.js借助事件驱动,非阻塞I/O模型变得轻量和高效,非常适合run ac ...

  4. log4j日志文件 log4j.xml log4j.properties配置

    1,导入log4j  jar包; 2,配置log4j.xml或log4j.properties文件; ------------------------------------------------- ...

  5. Git 常用命令行

    最近在公司的服务器上安装了Git Sever,开始从SVN转向到Git了,整理了一些在Git常用的命令. 取得Git仓库 初始化一个版本仓库 git initClone远程版本库 git clone ...

  6. JavaScript简单的tabel切换2

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. 20145205 《Java程序设计》第7周学习总结

    教材学习内容总结 认识时间与日期 1.格林威治时间(GMT):通过观察太阳而得,因为地球公转轨道为椭圆形且速度不一,本身自传减速而造成误差. 2.世界时(UT):通过观测远方星体跨过子午线而得,受地球 ...

  8. SQL SERVER 数据库操作脚本

    创建数据库 create Database MYDB on ( Name=mydb_dat, FileName='c:\data\mydate.mdf',size=10,maxsize=50 ) LO ...

  9. Linux下搭建Windows KMS服务器

    这几天微软发布了Windows 10 RedStone 1 Build 14390, 于是我第一时间下载进行了试用.和之前那种不激活也没有任何异样不同,现在的版本如果不激活有些功能就受限了,比如你无法 ...

  10. ArithUtil工具类 : 精确计算各种运算

    package com.autoserve.mh.common.util;   import java.math.BigDecimal; import java.text.DecimalFormat; ...