# LeetCode 425. Word Squares 单词平方

377人阅读 评论(0)

[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 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:

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

Example 1:

Input:

Output:

] ]

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

class Solution {
public:
vector<vector<string>> wordSquares(vector<string>& words){
//用hashtable存每个单词所有前缀
//参考代码：https://discuss.leetcode.com/topic/63387/java-ac-solution-easy-to-understand
n=words[0].size();
for(auto&word:words){
for(int i=0;i<n;i++){
mm[word.substr(0,i)].push_back(word);
}
}
helper(0);
return squares;
}
int n;
unordered_map<string,vector<string>> mm;
vector<string> square(n,string<n,"">);
vector<vector<string>> squares;

void helper(int i){
if(i==n){squares.push_back(square);return;}
string prefix;
for(int k=0;k<i;k++)
prefix+=square[i][k];
for(string&word:mm[prefix]){
square[i]=word;
helper(i+1);
}
}
//当用iterative比较复杂，代码量太大，则用recursive来写。
/*for(int i=0;i<words.size();i+=){
square[0]=words[i];
for(int j=0;j<n;j++){
for(int k=0;k<j;k++){
}
}
}*/
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：14373次
• 积分：2730
• 等级：
• 排名：第13228名
• 原创：270篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行