Leetcode 425. Word Squares

Problem:

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:

  1. There are at least 1 and at most 1000 words.
  2. All words will have the exact same length.
  3. Word length is at least 1 and at most 5.
  4. 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).

Solution:

  又是道恐怖的Trie的题目,这道题首先需要创建Trie数据结构,里面有个函数getStartsWith(TrieNode *r)是用DFS的方法获取所有从节点r开始的后缀。下面用Example1说明算法思路,path初始化为长宽均为4的字符串数组,首先遍历所有字符串先放满第一行和第一列,比如:

  ["wall",

   "a   ",

   "l   ",

   "l   "]

然后开始放第二行和第二列,此时我们需要用getStartsWith(TrieNode *r)函数获取前缀为a的所有后缀组合,并一个个尝试,其中一个结果为:

  ["wall",

   "area",

   "le   ",

   "la   "]

然后对于第三行和第三列找到前缀为le的所有后缀组合,以此类推,直到index为5即可。

Code:

 1 struct TrieNode{
 2     TrieNode *next[26];
 3     bool isEnd;
 4     TrieNode():isEnd(false){
 5         for(int i = 0;i != 26;++i)
 6             next[i] = NULL;
 7     }
 8 };
 9 class Trie{
10 public:
11     Trie(){
12         root = new TrieNode();
13     }
14     void insert(string &word){
15         TrieNode *current = root;
16         for(int i = 0;i != word.size();++i){
17             if(current->next[word[i]-‘a‘] == NULL){
18                 current->next[word[i]-‘a‘] = new TrieNode();
19             }
20             current = current->next[word[i]-‘a‘];
21         }
22         current->isEnd = true;
23     }
24     void dfs(TrieNode *r,string path,vector<string> &result){
25         if(r->isEnd){
26             result.push_back(path);
27             return;
28         }
29         for(int i = 0;i != 26;++i){
30             if(r->next[i] != NULL){
31                 dfs(r->next[i],path+(char)(i+‘a‘),result);
32             }
33         }
34     }
35     vector<string> getStartsWith(TrieNode *r) {
36         vector<string> result;
37         dfs(r,"",result);
38         return result;
39     }
40     TrieNode *getRoot(){
41         return root;
42     }
43 private:
44     TrieNode *root;
45 };
46 class Solution {
47 public:
48     void backtrace(int index,Trie &tree,TrieNode *root,vector<string> &path,vector<vector<string>> &result){
49         int m = path.size();
50         if(index == m){
51             result.push_back(path);
52             return;
53         }
54         TrieNode *current = root;
55         for(int i = 0;i != index;++i){
56             if(current->next[path[index][i]-‘a‘] == NULL)
57                 return;
58             current = current->next[path[index][i]-‘a‘];
59         }
60         vector<string> suffix = tree.getStartsWith(current);
61         for(int i = 0;i != suffix.size();++i){
62             for(int j = index;j != m;++j){
63                 path[index][j] = suffix[i][j-index];
64                 path[j][index] = suffix[i][j-index];
65             }
66             backtrace(index+1,tree,root,path,result);
67             for(int j = index;j != m;++j){
68                 path[index][j] = ‘ ‘;
69                 path[j][index] = ‘ ‘;
70             }
71         }
72     }
73     vector<vector<string>> wordSquares(vector<string>& words) {
74         Trie tree;
75         for(int i = 0;i != words.size();++i)
76             tree.insert(words[i]);
77         TrieNode *root = tree.getRoot();
78         int m = words[0].size();
79         vector<vector<string>> result;
80         vector<string> path(m,string(m,‘ ‘));
81         for(int i = 0;i != words.size();++i){
82             for(int j = 0;j != m;++j){
83                 path[0][j] = words[i][j];
84                 path[j][0] = words[i][j];
85             }
86             backtrace(1,tree,root,path,result);
87             for(int j = 0;j != m;++j){
88                 path[0][j] = ‘ ‘;
89                 path[j][0] = ‘ ‘;
90             }
91         }
92         return result;
93     }
94 };

原文地址:https://www.cnblogs.com/haoweizh/p/10204610.html

时间: 2024-10-02 18:55:32

Leetcode 425. Word Squares的相关文章

425. Word Squares

这题其实没什么,就是要在比较grid[i][j]和grid[j][i]的时候一方面要注意横着的那个单词的长度有没有超过grid的行数,一方面也要注意竖过来之后,横着的长度够不够这个位置的. 1 public boolean validWordSquare(List<String> words) { 2 if(words == null || words.size() == 0) { 3 return false; 4 } 5 for(int i = 0; i < words.size()

Leetcode: Word Squares &amp;&amp; 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 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 wor

[LeetCode] Word Squares 单词平方

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 wor

LeetCode:Word Pattern - 字符串模式匹配

1.题目名称 Word Pattern(字符串模式匹配) 2.题目地址 https://leetcode.com/problems/word-pattern/ 3.题目内容 英文:Given a pattern and a string str, find if str follows the same pattern. 中文:给出一组模式(pattern)和一个字符串(str),查看字符串是否与模式匹配 例如: pattern = "abba",str = "dog cat

【leetcode】Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, givens = "catsanddog",dict = ["cat", "cats"

【leetcode】Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true because &

LeetCode OJ - Word Ladder 2

我发现在leetcode上做题,当我出现TLE问题时,往往是代码有漏洞,有些条件没有考虑到,这道题又验证了我这一想法. 这道题是在上一道的基础上进一步把所有可能得转换序列给出. 同样的先是BFS,与此同时需要一个hashMap记录下每个节点,和他所有父节点的对应关系,然后通过DFS,回溯所有可能的路径. 下面是AC代码. 1 /** 2 * Given two words (start and end), and a dictionary, find all shortest transform

[LeetCode OJ] Word Search 深度优先搜索DFS

Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be us

Java for LeetCode 212 Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same le