标签:
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
题意:给出一个有n个单词的字典,问有多少不同的两个单词的组合使得新组合成的单词是回文串。
思路:对于每个单词,从左到右遍历一遍,对于任意一个位置,如果它的左边是回文串且右边的逆序在字典中出现,那么就存在这么一种组合,同理,如果它的右边是回文串且左边的逆序在字典中出现,那么也存在这么一种组合。
真是好题啊,涉及到好多知识点
不过还有个小疑问,为什么用 map 就超时了,用 unordered_map 就过了
http://blog.csdn.net/devourheavens/article/details/7539815
哈希map是一种关联容器,通过键值和映射值存储元素。允许根据键值快速检索各个元素。
134 / 134 test cases passed.
|
Status:
Accepted |
Runtime: 1804 ms
|
1 class Solution { 2 public: 3 vector<vector<int>> palindromePairs(vector<string>& words) { 4 vector<vector<int> > ans; 5 unordered_map<string,int> mp; 6 int n = words.size(); 7 int i,j; 8 for(i = 0;i < n;i++){ 9 mp[ words[i] ] = i; 10 } 11 12 for(i = 0;i < n;i++){ 13 int l = words[i].length(); 14 if(l == 0){ //空串 15 for(int k = 0;k < n;k++) 16 if(k != i && ispa(words[k])) ans.push_back(vector<int>{i,k}); 17 continue; 18 } 19 mp.erase(words[i]); //本身是回文的情况,会造成错误 20 for(j = 0;j < l;j ++){ 21 string subL = words[i].substr(0,j); 22 string subR = words[i].substr(j,l); 23 string revL,revR; 24 revL.assign(subL.rbegin(),subL.rend()); 25 revR.assign(subR.rbegin(),subR.rend()); 26 //j左边是回文,并且j右边的逆序找到(包括j) 27 if( mp.find(revR) != mp.end() && ispa(subL)){ 28 ans.push_back(vector<int>{mp[revR],i} ); 29 } 30 //j右边是回文,并且j左边的逆序找到(包括j) 31 if( mp.find(revL) != mp.end() && ispa(subR)){ 32 ans.push_back(vector<int>{i,mp[revL]} ); 33 } 34 } 35 mp[ words[i] ] = i; 36 } 37 return ans; 38 } 39 bool ispa(string& s) 40 { 41 int i = 0; 42 int l = s.length(); 43 int j = l - 1; 44 while(i <= j){ 45 if(s[i] != s[j]) return false; 46 i++;j--; 47 } 48 return true; 49 } 50 };
http://blog.csdn.net/y990041769/article/details/8763366
http://www.cnblogs.com/aicro/archive/2010/01/15/1642659.html
a) =,assign() //赋以新值
s.assign(b,e); 用迭代器b到e范围内的元素替换s
http://www.cnblogs.com/TianFang/archive/2006/12/30/607859.html
7。从map中删除元素
移除某个map中某个条目用erase()
该成员方法的定义如下
clear()就相当于 enumMap.erase(enumMap.begin(), enumMap.end());
leetcode 336. Palindrome Pairs
标签:
原文地址:http://www.cnblogs.com/njczy2010/p/5478314.html