Leetcode: Word Squares && Summary: Another Important Implementation of Trie(Retrieve all the words with a given Prefix)
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:
- Using a hashtable, key is prefix, value is a list of words with that prefix.
- 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)的更多相关文章
- [LeetCode] Word Squares 单词平方
Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- LeetCode Monotone Stack Summary 单调栈小结
话说博主在写Max Chunks To Make Sorted II这篇帖子的解法四时,写到使用单调栈Monotone Stack的解法时,突然脑中触电一般,想起了之前曾经在此贴LeetCode Al ...
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- [Lintcode]Word Squares(DFS|字符串)
题意 略 分析 0.如果直接暴力1000^5会TLE,因此考虑剪枝 1.如果当前需要插入第i个单词,其剪枝如下 1.1 其前缀(0~i-1)已经知道,必定在前缀对应的集合中找 – 第一个词填了ball ...
- Word Squares
Description Given a set of words without duplicates, find all word squares you can build from them. ...
- LC 425. Word Squares 【lock,hard】
Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...
- 【LeetCode】228. Summary Ranges 解题报告(Python)
[LeetCode]228. Summary Ranges 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/sum ...
- 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 ...
随机推荐
- 《DSP using MATLAB》示例Example5.14
代码: x1 = [1,2,2]; x2 = [1,2,3,4]; y = circonvt(x1,x2,4) n1 = 0:1:length(x1)-1; n2 = 0:1:length(x2)-1 ...
- C#连接Access数据库(详解)
做一个用VS2012的C#连接Access数据库的备忘, SQL数据库固然强大,有大微软的强力技术支持,LINQ的方便操作,但是如果写一个小程序对数据库方面没有什么大的要求的话,将来在数据库方面就可以 ...
- Daily Scrum Meeting ——NinthDay
一.Daily Scrum Meeting照片 二.Burndown Chart 三.项目进展 1.用户管理 2.下拉框与界面的整合 四.问题困难 黄志明(PM):Android Studio自带的S ...
- asp.net c# 网上搜集面试题目大全(附答案)
1.String str=new String("a")和String str = "a"有什么区别? String str = "a"; ...
- NOIP2008 ISBN号码(一桶水)【A005】
[A005]NOIP2008 ISBN号码(一大桶水)[难度A]———————————————————————————————————————————————————————————————————— ...
- iOS searchbar textfield placeholder color
// Get the instance of the UITextField of the search bar UITextField *searchField = [searchBar value ...
- 【转】前端工程筹建NodeJs+gulp+bower
转自:http://www.myexception.cn/javascript/1781968.html npm nodejs 安装过程中会自动安装npm,nodejs安装程序会在环境变量中添加两个变 ...
- Json.Net的简单使用
1.添加程序集 Newtonsoft.Json.dll 2.创建模型 public class Person { public string Name { get; set; } public ...
- SQl浅谈 索引
1.索引的工作原理 我给大家推荐一个别人的总结. http://blog.csdn.net/NightManHAHA/article/details/5648579 2.索引的设计原则 对于一张表来说 ...
- 从头到尾彻底理解KMP
从头到尾彻底理解KMP 作者:July 时间:最初写于2011年12月,2014年7月21日晚10点 全部删除重写成此文,随后的半个多月不断反复改进. 1. 引言 本KMP原文最初写于2年多前的201 ...