leetcode 336. Palindrome Pairs
来源:互联网 发布:大学生使用网络情况 编辑:程序博客网 时间:2024/06/07 10:29
336. Palindrome Pairs
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"]
暴力解题会超时。
把出现过的单词的长度挨个拿出来,搜索当前单词的除去该长度的部分。如果存在,那就能构成回文。
class Solution {public: vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> ret; map<string, int> mp; //存所有单词,方便后面搜索 set<int> st; //存单词出现过的长度 for (int i = 0; i < words.size(); i++) { mp[words[i]] = i; st.insert(words[i].size()); } for (int i = 0; i < words.size(); i++) { string s = words[i]; int len = s.size(); reverse(s.begin(), s.end()); if (mp.find(s) != mp.end() && mp[s] != i) //还不能是本身 { ret.push_back({i, mp[s]}); } for (auto it = st.begin(); it != st.end(), *it < len; it++) { if (ispalind(s.substr(0, len - *it)) && mp.find(s.substr(len - *it)) != mp.end()) { ret.push_back({i, mp[s.substr(len - *it)]}); } if (ispalind(s.substr(*it)) && mp.find(s.substr(0, *it)) != mp.end()) { ret.push_back({mp[s.substr(0, *it)], i}); } } } return ret; } bool ispalind(string s1) { string s2 = s1; reverse(s2.begin(), s2.end()); return s1 == s2; }};
阅读全文
0 0
- LeetCode 336. Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- leetcode 336. Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- leetcode.336. Palindrome Pairs
- [leetcode] 336. Palindrome Pairs
- LeetCode-336.Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- [LeetCode]336. Palindrome Pairs
- leetcode 336. Palindrome Pairs
- leetcode 336. Palindrome Pairs
- (Java)-LeetCode-336. Palindrome Pairs
- leetcode题解-336. Palindrome Pairs
- LeetCode 336. Palindrome Pairs(回文对)
- [leetcode] 336. Palindrome Pairs 解题报告
- leetcode 336. Palindrome Pairs 372. Super Pow
- [Leetcode] 336. Palindrome Pairs 解题报告
- [LeetCode]Palindrome Pairs
- PCL用PCLVisualizer显示点云之窗口黑屏
- 永恒之蓝封445端口方法
- shell反弹理解
- TCP/IP端口筛选
- Hibernate中createQuery与createSQLQuery两者的区别
- leetcode 336. Palindrome Pairs
- 阿里云服务器配置外网访问
- 【Dubbo实战】基础学习篇(一)
- GD2输出文字
- Tensorflow实战学习(四十一)【分布式并行】
- GD2实现给图像添加水印
- 快速学习Docker和容器技术
- GD2中文版水印
- hadoop的配置文件