Description

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
  • 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的更多相关文章

  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 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 ...

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

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

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

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

  5. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  6. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  7. Java Algorithm Problems

    Java Algorithm Problems 程序员的一天 从开始这个Github已经有将近两年时间, 很高兴这个repo可以帮到有需要的人. 我一直认为, 知识本身是无价的, 因此每逢闲暇, 我就 ...

  8. Hard模式题目

    先过一下Hard模式的题目吧.   # Title Editorial Acceptance Difficulty Frequency   . 65 Valid Number     12.6% Ha ...

  9. 继续过Hard题目

    接上一篇:http://www.cnblogs.com/charlesblc/p/6283064.html 继续过Hard模式的题目吧.   # Title Editorial Acceptance ...

随机推荐

  1. Delphi微信支付【支持MD5和HMAC-SHA256签名与验签】

    作者QQ:(648437169) 点击下载➨微信支付            微信支付api文档 [Delphi 微信支付]支持付款码支付.二维码支付.订单查询.申请退款.退款查询.撤销订单.关闭订单. ...

  2. - Gradle 翻译 Analyzer APK文件分析 MD

    目录 目录 APK文件分析 使用 APK 分析器分析您的编译版本 查看文件和大小信息 查看 AndroidManifest.xml 查看 DEX 文件 过滤DEX文件树视图 加载 Proguard 映 ...

  3. maven添加本地包命令mvn install:install-file

    mvn install:install .jar -Dfile:要注册的jar,绝对路径

  4. Kubernetes学习续之一键部署kubeadm

    1.Kubernetes的架构和组件,在部署时,它的每一个组件都是一个需要被执行的.单独的二进制文件,所以不难想象,SaltStack这样的运维工具或由社区维护的脚本的功能,就是要把这些二进制文件传输 ...

  5. 示例:WPF实现ApplicationCommands.Delete的TextBox

    原文:示例:WPF实现ApplicationCommands.Delete的TextBox 目的:通过模仿TextBox中Ctrl+C等快捷键原理来了解CommandBindings实现原理,可以通过 ...

  6. ASP.NET Core应用程序的参数配置及使用(转载)

    本文结构 提前准备 参数配置方式 appsettings.json 环境变量 命令行参数 在控制器中使用配置参数 注入IConfiguration对象 注入IOptions对象 总结 应用程序的开发不 ...

  7. 一文搞懂 Flink 网络流控与反压机制

    https://www.jianshu.com/p/2779e73abcb8 看完本文,你能get到以下知识 Flink 流处理为什么需要网络流控? Flink V1.5 版之前网络流控介绍 Flin ...

  8. 关于win server中 task Scheduler使用

    日常开发过程中最会遇到很多定时任务,利用计算机自带的软件工具,既方便,又快捷,能节省大量的开发时间,而且功能全面,容错率高. 下面举个例子:定时发送邮件,每天8:10准时触发邮件发送脚本 1.首先配置 ...

  9. C#读写修改设置调整UVC摄像头画面-全景

    有时,我们需要在C#代码中对摄像头的全景进行读和写,并立即生效.如何实现呢? 建立基于SharpCamera的项目 首先,请根据之前的一篇博文 点击这里 中的说明,建立基于SharpCamera的摄像 ...

  10. jsMind思维导图模式展示数据

    效果图: jsmind组件下载地址:https://files.cnblogs.com/files/fengyeqingxiang/jsmind.zip 后端代码,此处以C#编写的后台,Java或其他 ...