第十六周算法题
来源:互联网 发布:mysql复合主键的优缺点 编辑:程序博客网 时间:2024/06/09 14:30
336. Palindrome Pairs
DescriptionHintsSubmissionsSolutions
- Total Accepted: 24269
- Total Submissions: 94125
- Difficulty: Hard
- Contributor: LeetCode
Given a list of unique words, find all pairs of distinct indices (i, j)
in the given list, so that the concatenation of the two words, i.e.words[i] + words[j]
is a palindrome.
Example 1:
Given words
= ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words
= ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
代码如下:
class Solution {public: vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> res; if (!words.size()) return res; unordered_map<string, size_t> word_idx; for (size_t i = 0; i < words.size(); ++i) { word_idx[words[i]] = i; } vector<int> slu(2); for (size_t i = 0; i < words.size(); ++i) { size_t len = words[i].length(); for (size_t l = 0; l <= len; ++l) { string left = words[i].substr(0, l); string right = words[i].substr(l); string rleft = left; string rright = right; reverse(rleft.begin(), rleft.end()); reverse(rright.begin(), rright.end()); if (word_idx.find(rleft) != word_idx.end()) { if (word_idx[rleft] != i && isPalindrome(right)) { slu[0] = i; slu[1] = word_idx[rleft]; res.push_back(slu); } } if (l != 0 && word_idx.find(rright) != word_idx.end()) { if (word_idx[rright] != i && isPalindrome(left)) { slu[0] = word_idx[rright]; slu[1] = i; res.push_back(slu); } } } } return res; } bool isPalindrome(string s) { if (s.size() <= 1) return true; size_t i = 0; size_t j = s.size() - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; }};
阅读全文
0 0
- 第十六周算法题
- 第十六周 验证算法--基数排序
- 算法第十六周作业01
- 第十六周LeetCode算法题两道
- 第十六周--验证算法(插入排序)
- 第十六周--验证算法(希尔排序)
- 第十六周--验证算法(快速排序)
- (第十六周项目1)验证算法
- 第十六周--验证算法(堆排序)
- 第十六周 项目1.1- 验证算法
- 第十六周--验证算法(归并排序)
- 第十六周--验证算法(基数排序)
- 第十六周--验证算法(冒泡排序)
- 第十六周 项目1.2- 验证算法
- 第十六周 项目1.3- 验证算法
- 第十六周--归并排序算法的改进
- 第十六周 项目1 验证算法 基数排序
- 第十六周--项目5算法验证基数排序
- <context:component-scan>使用说明
- 用Apache James搭建邮件服务器收发邮件
- URLClassLoader使用方法和实例
- BMW车辆四轮定位的一般步骤
- IntentService初步应用和实例介绍
- 第十六周算法题
- 06-图3 六度空间 (30分)
- 用scrapy 模拟知乎的登录过程
- MySQL 基本操作
- 为什么说软件外包公司没前途
- 微信支付开发(1) JS API支付
- 用JS完成注册页面的一个简单校验
- 针对 CoordinatorLayout 及 Behavior 的一次细节较真
- Processing Images(处理图像)