求解性思维与验证性思维
题目分析:
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"]
/** * 论求解性思维与验证性思维 * * 本题很直观的想法是验证性思维:一一去验证每个可能性, * 时间复杂度O(n^2*k),n为字符串的数量,k为字符串的长度 * 显然这种方法对于n不是很大的情况比较适用,当n比较大时效率就太低 * * 如果采用求解性思维,那么我们只需要找对于每个字符串与其可以构成回文字符串的字符串 * 是否存在即可,时间复杂度O(n * k^2 ),对于k不是很大的情况下比较适用,当k太大是效率 * 也是比较低的。通过提交发现本题适合第二种情况 * * 总结:求解性思维与验证性思维是算法中常见的两位基本思维方式,对于不同的题目两种算法 * 的效率也是不同的。验证性思维与二分法的结合是经常出现的一个知识点,一般情况下如果有 * 好的求解方案,求解性思维的效率是很高的。当然具体题目具体分析 * * ps(正向思维与逆向思维也是两种常见的思想) **/ class Solution { public: bool ispalindrome(string &st) { int u = 0, v = st.size() - 1; while(u <= v) { if(st[u] != st[v]) break; ++u; --v; } if(u > v) return true; else return false; } vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> ans; int tans[2]; unordered_map<string, int> ump; for(size_t i = 0; i != words.size(); ++i) { string st = words[i]; reverse(st.begin(), st.end()); ump[st] = i; } for(size_t i = 0; i != words.size(); ++i) { if(ispalindrome(words[i]) && ump.find("") != ump.end() && ump[""] != i) { tans[0] = i; tans[1] = ump[""]; ans.push_back(vector<int>(tans, tans + 2)); tans[0] = ump[""]; tans[1] = i; ans.push_back(vector<int>(tans, tans + 2)); } } for(size_t i = 0; i != words.size(); ++i) { if(ump.find(words[i]) != ump.end() && ump[words[i]] != i) { tans[0] = i; tans[1] = ump[words[i]]; ans.push_back(vector<int>(tans, tans + 2)); } for(size_t j = 1; j < words[i].size(); ++j) { string left, right; left = words[i].substr(0, j); right = words[i].substr(j, words[i].size() - j); if(ispalindrome(right) && ump.find(left) != ump.end()) { tans[0] = i; tans[1] = ump[left]; ans.push_back(vector<int>(tans, tans + 2)); } if(ispalindrome(left) && ump.find(right) != ump.end()) { tans[0] = ump[right]; tans[1] = i; ans.push_back(vector<int>(tans, tans + 2)); } } } return ans; } };