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. 【转载】Linux(CentOS)下安装Redis

    转载地址:https://blog.csdn.net/diweikang/article/details/78784631 1.下载Redis下载最新Linux版本的Redis,我用的是redis-4 ...

  2. MQTTv5.0 ---AUTH – 认证交换

    AUTH报文被从客户端发送给服务端,或从服务端发送给客户端,作为扩展认证交换的一部分,比如质询/ 响应认证.如果CONNECT报文不包含相同的认证方法,则客户端或服务端发送AUTH报文将造成协议错 误 ...

  3. -Git Linux vi/vim 命令 按键 MD

    目录 目录 Linux vi/vim 简介 vi/vim 的使用 命令模式 输入模式 底线命令模式 vi/vim 使用实例 使用 vi/vim 进入一般模式 按下 i 进入输入模式,开始编辑文字 按下 ...

  4. 踏入OpenGL大门 —— VS2015开发环境配置 (详细图文)

    转自: https://www.jianshu.com/p/68c314fa9fea?from=groupmessage   眼睛熊 ---------------- 本文 ------------- ...

  5. CMPP服务端源码

    CMPP服务端,带数据库,可以接收第三方CMPP客户端的短信,并存入数据库,结合我的cmpp客户端服务程序,将可以实现接收第三方SP的短信并转发到网关实现发送,并将状态报告.上行短信转发给第三方SP, ...

  6. Java的Annnotation (注解)

    注解是什么呢? 其实就像商场的商品上都贴有自己的标签一样,它提供了关于这个商品的许多额外信息.你可以根据这些信息对其进行附加的处理. (Java的语法糖果然比较差劲), 这个name()方法太累赘了, ...

  7. Java 之 Scanner 类

    一.Scanner 类 Scanner 是一个可以解析基本类型和字符串的简单文本扫描器. Demo: Scanner sc = new Scanner(System.in); int i = sc.n ...

  8. 12 ARM汇编

    Android系统采用java作为平台软件基础开发语言,NDK使Android平台可以运行C/C++代码这些代码汇编成ARM的elf可执行文件. 原生程序生成过程 经历4步:1.预处理2.编译3.汇编 ...

  9. Kafka Streams开发入门(2)

    背景 上一篇我们介绍了Kafka Streams中的消息转换操作map,今天我们给出另一个经典的转换操作filter的用法.依然是结合一个具体的实例展开介绍. 演示功能说明 本篇演示filter用法, ...

  10. ip黑名单-做过ssh扫描黑的ip

    # # hosts.deny This file contains access rules which are used to # deny connections to network servi ...