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 ...
随机推荐
- [转帖]分布式锁-redLock And Redisson
分布式锁-redLock And Redisson 2019-03-01 16:51:48 淹不死的水 阅读数 372更多 分类专栏: 分布式锁 版权声明:本文为博主原创文章,遵循CC 4.0 B ...
- Mysql 学习参考
[1]Mysql 基础知识 (1)<Mysql 官网> (2)<菜鸟教程之Mysql数据库教程> (3)<C语言中文网之Mysql数据库栏> (4)<W3Sc ...
- B树和B+树的增/删结点(转)
add by zhj: 算法其实不复杂,尤其是增加结点的算法,逻辑很简单,但有时自己想不到. 增加结点算法:首先,对于B树,没有重复结点,所以新插入的数据一定会落在叶结点上,或者说落在叶结点的所有父结 ...
- Queue介绍
美人如斯! 前言 队列是一种先进先出(FIFO)的数据结构,与生活中的排队类似,即先来先被服务,这样的特点决定了其具有一定的优先级含义,可以被用于任务调度等场景.队列模型如图: 图1.队列模型 jav ...
- win10下apache superset的使用
官方文档:http://superset.apache.org/ 一.环境准备 安装python3即3.4以上版本 二.python创建一个虚拟环境用来作为superset的容器 -pip3 inst ...
- python matplotlib 设置x轴文本间隔显示(数字的话可以转为字符之后处理)
一个国际友人绘图遇到的问题,查了一手资料.主要参考的是这个老哥的做法(https://blog.csdn.net/wyquin/article/details/80508260) #totalSeed ...
- Mycat分布式数据库架构解决方案--搭建MySQL读写分离环境--一主多从
echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!!! 本文主 ...
- 2019-08-02 原生ajax搜索
<html> <meta charset="utf-8"/> <head><title>搜索页</title></ ...
- js中函数的参数为函数的情况即回调函数
js中函数的参数可以是数组对象也可以是函数,当参数为函数时我们叫做回调函数 //定义回调函数function B() { console.log("函数B")setTimeout( ...
- centos7快速安装coreDns
1.下载二进制文件 wget https://github.com/coredns/coredns/releases/download/v1.5.0/coredns_1.5.0_linux_amd64 ...