LeetCode #336 - Palindrome Pairs

本文介绍了一种算法,用于在给定的唯一单词列表中找出所有可能的回文串对。通过实例演示了如何使用该算法来找到满足条件的回文组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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:

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:

Input: ["bat","tab","cat"]

Output: [[0,1],[1,0]] 

Explanation: The palindromes are ["battab","tabbat"]

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        unordered_map<string, int> hash;
        for(int i=0;i<words.size();i++) hash[words[i]]=i;
        
        vector<vector<int>> result;
        for(int i=0;i<words.size();i++)
        {
            for(int j=0;j<=words[i].size();j++)
            {
                string s1=words[i].substr(0,j);
                string s2=words[i].substr(j);
                //判断bbabc和cba的情况或"a"和""或"abc"和"cba"
                if(isPalindrome(s1)) //j==words[i].size()时,可以拆分成""和"abc"
                {
                    string s3=s2;
                    reverse(s3.begin(),s3.end());
                    if(hash.count(s3)>0&&hash[s3]!=i) 
                    {   
                        result.push_back({hash[s3],i});
                    }
                }
                //判断abcbb和cba的情况或""和"a"
                if(isPalindrome(s2)&&j<words[i].size()) //加入j<words[i].size(),为了避免拆分成"abc"和""与之前重复
                {
                    string s3=s1;
                    reverse(s3.begin(),s3.end());
                    if(hash.count(s3)>0&&hash[s3]!=i) 
                    {
                        result.push_back({i,hash[s3]});
                    }
                }
            }
        }
        return result;
    }
    
    bool isPalindrome(string s)
    {
        int i=0;
        int j=s.size()-1;
        while(i<=j) 
        {
            if(s[i]!=s[j]) return false;
            i++;
            j--;
        }
        return true;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值