Palindrome Pairs
題目來源
給一個字串陣列,求能組成迴文串的兩個元素的。
就是比較煩,但是倒不是很難。
程式碼如下:
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
int len = words.size();
unordered_map<string, int> maps;
vector<vector<int>> res;
for (int i=0; i<len; i++) {
if (words[i] == "")
continue;
maps[words[i]] = i;
}
for (int i=0; i<len; i++) {
int wordLen = words[i].size();
if (wordLen == 0)
for (int j=0; j<len; j++) {
if (i != j && isPalindrome(words[j])) {
res.push_back(vector<int>{i, j});
res.push_back(vector<int>{j, i});
}
}
for (int j=wordLen; j>=1; j--) {
string left = words[i].substr(0, j);
string right = words[i].substr(j);
bool isleft = isPalindrome(left);
bool isright = isPalindrome(right);
reverse(left.begin(), left.end());
reverse(right.begin(), right.end());
if (isright && maps.count(left) != 0 && maps[left] != i) {
vector<int> pair{i, maps[left]};
res.push_back(pair);
}
if (isleft && maps.count(right) != 0 && maps[right] != i) {
vector<int> pair{maps[right], i};
res.push_back(pair);
}
}
}
return res;
}
bool isPalindrome(string &str)
{
if (str == "")
return true;
int p1 = 0, p2 = str.size() - 1;
while (p1 < p2) {
if (str[p1] != str[p2])
return false;
p1++;
p2--;
}
return true;
}
};
相關文章
- LeetCode-Palindrome PairsLeetCodeAI
- 【LeetCode】Palindrome Pairs(336)LeetCodeAI
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- Swap Nodes in PairsAI
- 024,Swap Nodes in PairsAI
- 24. Swap Nodes in PairsAI
- Leetcode Swap Nodes in PairsLeetCodeAI
- CF1762F Good PairsGoAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- 【Lintcode】572. Music PairsAI
- 1512. Number of Good PairsGoAI
- 532. K-diff Pairs in an ArrayAI
- LeetCode 24 Swap Nodes in PairsLeetCodeAI
- Leetcode-Swap Nodes in PairsLeetCodeAI
- Swap Nodes in Pairs leetcode javaAILeetCodeJava
- leetcode Palindrome NumberLeetCode
- D - Avoid K Palindrome
- Vim auto-pairs設定選項AI
- CF Div. 3 C Beautiful Triple PairsAI
- 搞定字串類面試題-Palindrome字串面試題
- Leetcode 9 Palindrome NumberLeetCode
- Leetcode Valid PalindromeLeetCode
- Palindrome Number leetcode javaLeetCodeJava
- Diff-prime Pairs(思維+素數篩)AI
- LeetCode677. Map Sum PairsLeetCodeAI
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- Leetcode 線性表 Swap Nodes in PairsLeetCodeAI
- E - Remove Pairs(狀壓dp+博弈論)REMAI
- [LeetCode] 9. Palindrome NumberLeetCode
- LeetCode-Palindrome Permutation IILeetCode
- LeetCode-Valid PalindromeLeetCode
- Leetcode: Palindrome Partitioning IILeetCode
- [LintCode] Palindrome Linked List
- LeetCode - 9. Palindrome NumberLeetCode
- Leetcode Palindrome Linked ListLeetCode
- Valid Palindrome leetcode javaLeetCodeJava
- Palindrome Partitioning leetcode javaLeetCodeJava
- Lua中ipairs()和pairs()的區別與使用AI