前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0336 - Palindrome Pairs

LeetCode 0336 - Palindrome Pairs

作者头像
Reck Zhang
发布2021-08-11 11:21:31
2550
发布2021-08-11 11:21:31
举报
文章被收录于专栏:Reck Zhang

Palindrome Pairs

Desicription

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:

代码语言:javascript
复制
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]] 
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

Example 2:

代码语言:javascript
复制
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]] 
Explanation: The palindromes are ["battab","tabbat"]

Solution

代码语言:javascript
复制
class Solution {
public:
    std::vector<std::vector<int>> palindromePairs(std::vector<std::string>& words) {
        auto res = std::vector<std::vector<int>>();
        auto indexMap = std::map<std::string, int>();
        auto sizeSet = std::set<int>();

        for(int i = 0; i < words.size(); i++) {
            indexMap.insert({words[i], i});
            sizeSet.insert(words[i].size());
        }

        for(int i = 0; i < words.size(); i++) {
            auto word = words[i];
            std::reverse(word.begin(), word.end());

            if(indexMap.find(word) != indexMap.end() && indexMap[word] != i) {
                res.push_back({i, indexMap[word]});
            }

            auto rightIterator = sizeSet.find(word.size());
            for(auto it = sizeSet.begin(); it != rightIterator; it++) {
                if(isPalindrome(word, 0, word.size() - *it - 1) && indexMap.find(word.substr(word.size() - *it)) != indexMap.end()) {
                    res.push_back({i, indexMap[word.substr(word.size() - *it)]});
                }

                if(isPalindrome(word, *it, word.size() - 1) && indexMap.find(word.substr(0, *it)) != indexMap.end()) {
                    res.push_back({indexMap[word.substr(0, *it)], i});
                }
            }
        }

        return res;
    }

private:
    static bool isPalindrome(const std::string &word, int left, int right) {
        while(left < right) {
            if(word[left++] != word[right--]) {
                return false;
            }
        }
        return true;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Palindrome Pairs
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档