LeetCode No336. Palindrome Pairs

1. 题目描述

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”]

2. 思路

通俗解法如下,时间复杂度为O(n^2 * k). k为单词的位数, n为单词数量

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        vector<vector<int>> ret;
        for (int i = 0; i < words.size(); ++i) {
            for (int j = 0; j < words.size(); ++j) {
                if (i == j)  continue;
                string s = words[i] + words[j];
                if (IsPalindrome(s)) 
                    ret.push_back(vector<int>{i, j});
            }
        }
        return ret;
    }
private:
    bool IsPalindrome(const string &s) {
        for (int left = 0, right = s.size() - 1; left < right; ++left, --right) {
            if (s[left] != s[right])  return false;
        }
        return true;
    }
};

结合无序容器和回文的一些特征有如下解法:
Assumption: No duplicated string in the given dictionary

Steps:

  1. Traverse the array, build map. Key is the reversed string, value is index in array (0 based)

  2. Edge case - check if empty string exists. It’s interesting that for given words {“a”, “”}, it’s expected to return two results [0,1] and [1,0]. Since my main logic can cover [0, 1] concatenate(“a”, “”), so as to cover the other situation concatenate(“”, “a”), I need to traverse the words array again, find the palindrome word candidate except “” itself, and add pair(“”, palindrome word) to the final answer.

  3. Main logic part. Partition the word into left and right, and see 1) if there exists a candidate in map equals the left side of current word, and right side of current word is palindrome, so concatenate(current word, candidate) forms a pair: left | right | candidate. 2) same for checking the right side of current word: candidate | left | right.

3. 代码及复杂度分析

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        vector<vector<int>> ret;
        unordered_map<string, int> dict;

        for (int i = 0; i < words.size(); ++i) {
            string s = words[i];
            reverse(s.begin(), s.end());
            dict[s] = i;
        }

        for (int i = 0; i < words.size(); ++i) {
            for (int j = 0; j < words[i].size(); ++j) {
                string left = words[i].substr(0, j);
                string right = words[i].substr(j, words[i].size() - j);
                if (dict.find(left) != dict.end() && IsPalindrome(right) && dict[left] != i) {
                    ret.push_back({i, dict[left]});
                    if (left.empty()) {
                        ret.push_back({dict[left], i});
                    }
                }
                if (dict.find(right) != dict.end() && IsPalindrome(left) && dict[right] != i) {
                    ret.push_back({dict[right], i});
                }

            }
        }
        return ret;
    }
private:
    bool IsPalindrome(const string &s) {
        for (int left = 0, right = s.size() - 1; left < right; ++left, --right) {
            if (s[left] != s[right])  return false;
        }
        return true;
    }
};

时间复杂度为: O(n * k^2), 其中n为单词的数量,k为单词的位数。

4. 参考资料

  1. https://leetcode.com/discuss/93599/easy-to-understand-ac-c-solution-o-n-k-2-using-map
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值