Word Squares
Description
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
- 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
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"]]
思路:字典树+dfs。
根据已添加单词确定下一个单词的前缀,利用dfs搜索。
public class Solution {
class TrieNode {
List<String> startWith;
TrieNode[] children;
TrieNode() {
startWith = new ArrayList<>();
children = new TrieNode[26];
}
}
class Trie {
TrieNode root;
Trie(String[] words) {
root = new TrieNode();
for (String w : words) {
TrieNode cur = root;
for (char ch : w.toCharArray()) {
int idx = ch - 'a';
if (cur.children[idx] == null)
cur.children[idx] = new TrieNode();
cur.children[idx].startWith.add(w);
cur = cur.children[idx];
}
}
}
List<String> findByPrefix(String prefix) {
List<String> ans = new ArrayList<>();
TrieNode cur = root;
for (char ch : prefix.toCharArray()) {
int idx = ch - 'a';
if (cur.children[idx] == null)
return ans;
cur = cur.children[idx];
}
ans.addAll(cur.startWith);
return ans;
}
}
public List<List<String>> wordSquares(String[] words) {
List<List<String>> ans = new ArrayList<>();
if (words == null || words.length == 0)
return ans;
int len = words[0].length();
Trie trie = new Trie(words);
List<String> ansBuilder = new ArrayList<>();
for (String w : words) {
ansBuilder.add(w);
search(len, trie, ans, ansBuilder);
ansBuilder.remove(ansBuilder.size() - 1);
}
return ans;
}
private void search(int len, Trie tr, List<List<String>> ans,
List<String> ansBuilder) {
if (ansBuilder.size() == len) {
ans.add(new ArrayList<>(ansBuilder));
return;
}
int idx = ansBuilder.size();
StringBuilder prefixBuilder = new StringBuilder();
for (String s : ansBuilder)
prefixBuilder.append(s.charAt(idx));
List<String> startWith = tr.findByPrefix(prefixBuilder.toString());
for (String sw : startWith) {
ansBuilder.add(sw);
search(len, tr, ans, ansBuilder);
ansBuilder.remove(ansBuilder.size() - 1);
}
}
}
Word Squares的更多相关文章
- [LeetCode] Word Squares 单词平方
Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...
- 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 ...
- [Lintcode]Word Squares(DFS|字符串)
题意 略 分析 0.如果直接暴力1000^5会TLE,因此考虑剪枝 1.如果当前需要插入第i个单词,其剪枝如下 1.1 其前缀(0~i-1)已经知道,必定在前缀对应的集合中找 – 第一个词填了ball ...
- 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 All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- LeetCode All in One题解汇总(持续更新中...)
突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...
- Java Algorithm Problems
Java Algorithm Problems 程序员的一天 从开始这个Github已经有将近两年时间, 很高兴这个repo可以帮到有需要的人. 我一直认为, 知识本身是无价的, 因此每逢闲暇, 我就 ...
- Hard模式题目
先过一下Hard模式的题目吧. # Title Editorial Acceptance Difficulty Frequency . 65 Valid Number 12.6% Ha ...
- 继续过Hard题目
接上一篇:http://www.cnblogs.com/charlesblc/p/6283064.html 继续过Hard模式的题目吧. # Title Editorial Acceptance ...
随机推荐
- Excel批量添加不同的批注
Sub 批量添加不同批注() Dim rng As Range Dim i As String Range("A1:D1").ClearComments For Each rng ...
- Elasticsearch常见用法-入门
前台启动 默认是只有本地可以访问 ./bin/elasticsearch 远程访问 修改elasticsearch.yml,把network.host(注意配置文件格式不是以 # 开头的要空一格, : ...
- Kafka学习笔记之如何永久删除Kafka的Topic
0x00 问题描述 使用kafka-topics --delete命令删除topic时并没有真正的删除,而是把topic标记为:“marked for deletion”,导致重新创建相同名称的Top ...
- Mybatis+MySql 一个标签中执行多条sql语句
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/cxfly957/article/details/77896590 MySql默认是不支持这种骚操作的 ...
- Apache配置WebSocket代理
引入mod_proxy_wstunnel.so模块,使其可以解析ws.wss协议 LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel ...
- 【转载】UiPath,UiPath教程,UiPath视频教程 RPA
第一课-UiPath简介 第二课-变量和数据类型第1部分-基础讲解 第二课-变量和数据类型第2部分-实例讲解 第二课-流程控制第1部分-ifelse语句讲解 第二课-流程控制第3部分-高级流程控制语句 ...
- MFC中窗口重绘
搬家于CSDN 2015-05-14 MFC提供了三个函数用于窗口重绘 InvalidateRect(&Rect) Invalidate() UpdateWindow() 当需要更新或者重绘窗 ...
- python 日期、时间、字符串相互转换
python 日期.时间.字符串相互转换 在python中,日期类型date和日期时间类型dateTime是不能比较的. (1)如果要比较,可以将dateTime转换为date,date不能直接转换为 ...
- 【转载】C#中ArrayList集合类使用RemoveAt方法移除指定索引的元素
ArrayList集合是C#中的一个非泛型的集合类,是弱数据类型的集合类,可以使用ArrayList集合变量来存储集合元素信息,任何数据类型的变量都可加入到同一个ArrayList集合中,在Array ...
- 石油petrolaeum单词petrolaeum原油
petroleum 1.a flammable liquid ranging in color from clear to very dark brown and black, consisting ...