博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LC 425 word squares
阅读量:6905 次
发布时间:2019-06-27

本文共 2172 字,大约阅读时间需要 7 分钟。

Given a set of words (without duplicates), find all  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 la r e al e a dl 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).
class Solution {public:    vector
> wordSquares(vector
& words) { vector
> res; unordered_map
> m; int n = words[0].size(); for (string word : words) { for (int i = 0; i < n; ++i) { string key = word.substr(0, i); m[key].insert(word); } } vector
> mat(n, vector
(n)); helper(0, n, mat, m, res); return res; } void helper(int i, int n, vector
>& mat, unordered_map
>& m, vector
>& res) { if (i == n) { vector
out; for (int j = 0; j < n; ++j) out.push_back(string(mat[j].begin(), mat[j].end())); res.push_back(out); return; } string key = string(mat[i].begin(), mat[i].begin() + i); for (string str : m[key]) { mat[i][i] = str[i]; int j = i + 1; for (; j < n; ++j) { mat[i][j] = str[j]; mat[j][i] = str[j]; if (!m.count(string(mat[j].begin(), mat[j].begin() + i + 1))) break; } if (j == n) helper(i + 1, n, mat, m, res); } }};

 

 

转载于:https://www.cnblogs.com/jxr041100/p/8440348.html

你可能感兴趣的文章
《跟菜鸟学Cisco UC部署实战》-上线了(线下培训班开班,见百度云)
查看>>
SANS:2016年网络威胁情报现状调研报告
查看>>
python模块paramiko的上传下载和远程执行命令方法
查看>>
做了8年电商 我发现这6种靠谱的电商运营管理思维
查看>>
成长型企业需要什么样的光纤存储
查看>>
Python中执行系统命令常见的几种方法
查看>>
物联网改变生活——飞思卡尔技术论坛中国站侧记
查看>>
Microsoft NLayerApp案例理论与实践 - 领域模型层
查看>>
【转】MFC 连接SQL SERVER(ODBC方式)
查看>>
SAP屏幕设计器专题:表格控件(六)
查看>>
回到正轨
查看>>
Emacs快捷键 绑定 中文
查看>>
[转]php伪静态
查看>>
LINUX下PHP运行环境搭建之三(转)
查看>>
asp.net中连接字符串问题(类库中使用ConfigurationManager.ConnectionStrings)
查看>>
[轉]批处理命令手册
查看>>
.NET连接SAP系统专题:.NET调用RFC几种方式(一)
查看>>
[转]让工作变得高效而简单的10种方法
查看>>
艾伟_转载:Web网站缓存文件并发问题解决方案
查看>>
HTML5和CSS3参考资源与教程
查看>>