[leetcode] 336. Palindrome Pairs

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

解题思路
本题难度为hard, 作为算法小菜鸟,能想到的方法只有暴力循环法,两层循环把字符串拼在一起,然后判断是否为回文串,结果果然超时。好在网上有大神分享自己的解法,选了一种比较好理解的方法,在这里总结一下。

  • 遍历数组,翻转每一个字符串,将翻转后的字符串和下标存入哈希表hash。
  • 遍历数组,针对每个字符串在任意位置将其分为左右两个部分,ls和rs, 分别判断ls和rs是否是回文,如果ls是回文,那么判断rs是否存在于hash之中,如果存在,(假设rs翻转为sr),则sr-ls-rs构成回文串。同理,rs也回文的情况也一样。
  • 复杂度分析:假设字符串的平均长度为k,数组长度为n, 第一层循环为n,第二次循环为k, 判断回文为k,因此复杂度为O(nkk)

具体代码如下:

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        vector<vector<int> > result;
        unordered_map<string,int> dict;
        int size = words.size();
        
        string left, right,tmp;
        for(int i = 0; i < size; ++i)
        {
            tmp = words[i];
            reverse(tmp.begin(),tmp.end());
            dict[tmp] = i;
        }
        
        for(int i = 0; i < size; ++i)
        {
            for(int j = 0; j < words[i].size(); ++j)
            {
                left = words[i].substr(0,j);
                right = words[i].substr(j);
                if(dict.find(left) != dict.end() && dict[left] != i && isPalindrome(right))
                {
                    result.push_back({i, dict[left]});
                    if(left.empty())//如果为空单独判断
                        result.push_back({dict[left],i});
                }
                if(dict.find(right) != dict.end() && dict[right] != i &&
                    isPalindrome(left))
                {
                    result.push_back({dict[right], i}); 
                }
                
            }
        }
        
        return result;
    }
    
private:
    bool isPalindrome(string s)
    {
        int left = 0, right = s.size() - 1;
        while(left < right)
        {
            if(s[left] != s[right])
                return false;
            left++;
            right--;
            
        }
        return true;
    }
};

参考资料:https://discuss.leetcode.com/topic/40654/easy-to-understand-ac-c-solution-o-n-k-2-using-map/5

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • 6月26日值得纪念的日子,希望一切安好顺利!保佑一切顺利!此刻,五好先生正睡觉!一切都刚刚好!
    gfy燕子阅读 239评论 0 0
  • 想跟你说话,想跟你分享我身边发生的全部,包括夜里醒来口渴的感觉,晚餐时弄到衣口的污渍,还有巷子里那只很乖的小狗,和...
    乌了八突阅读 282评论 1 0
  • Web开发的基本流程 a. 用户向Web服务器请求一个文档;b. Web服务器随即获取或生成这个文档;c. 服务器...
    偷天神猫阅读 947评论 0 0