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 ...
随机推荐
-
如何从NFS文件系统启动
笔记,备忘! 步骤: 1.设置好NFS服务器 2.修改uboot启动参数bootarg setenv bootargs console=ttySAC0 root=/dev/nfs nfsroot=19 ...
-
PHP函数——parse_ini_file() 函数
资料网址:http://www.w3school.com.cn/php/func_filesystem_parse_ini_file.asp 1.parse_ini_file() 函数解析一个配置文件 ...
-
Js全选,插入实现
//全选 function CheckAll() { ids.splice(0, 1000000); var flag = $("#All_Check").attr("c ...
-
windows mobile仿真器内存调整
1.打开VS,进入工具,选项. 2.点击设备,在右侧选中要调整的模拟器,点属性. 3.点击仿真器选项. 4.勾选 指定RAM大小. 5.重启仿真管理器.
-
基于AE连通性分析
曾经做管线连通性分析,总觉得ARCGIS应该有现成的方案可以实现,但最终没有找到,后来只好自己写了套代码,但在搜索过程中找到了这样一估代码,当时留了下来,那我现在也把它留下来. Dim pLayer ...
-
CCS v5 无法启动解决办法及Launchpad仿真器电脑无法识别解决方法
安装ccs_setup_5.1.1.00028.exe后(无论是自己装eclipse还是在原来的基础上安装eclipse的插件),ccs5的应用无法打开,错误为:An error has occurr ...
-
HDU 2546 饭卡(01背包裸题)
饭卡 Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submiss ...
-
ASP.NET Core中的Startup类
ASP.NET Core程序要求有一个启动类.按照惯例,启动类的名字是 "Startup" .Startup类负责配置请求管道,处理应用程序的所有请求.你可以指定在Main方法中使 ...
-
C# EF 与 MySql 的那些坑
之前一直想用 mysql 和 ef .然后多次尝试也只能感叹 还是 sqlsever 是亲儿子. 今天在单位又尝试了一次,然后就成功了,记录一下遇到的问题. 首先是安装包和驱动?. 请保证 MySql ...
-
EXSI6.5复制文件太慢的解决方法
听说裸金属服务器性能比在windows中安装VMware workstations要好,就在电脑上安装了一个EXSI6.5. 可是在复制文件时很慢,一个3G的文件复制了两三个小时,还时常担心网络会断, ...