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.

题目大意

在字符串数组中找两个不同的字符串,若这两个字符串能拼接成回文串,则将两个字符串的索引存到结果中。

示例

E1

Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]] 
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

E2

Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]] 
Explanation: The palindromes are ["battab","tabbat"]

解题思路

用map存储字符串的索引关系,并遍历字符串数组,依次查找该字符串可能的回文串组合,并在map中查找是否存在,若存在则将其加入结果。

复杂度分析

时间复杂度:O(N * K2)

空间复杂度:O(N)

代码

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        map<string, int> index;
        vector<vector<int> > res;
        
        for(int i = 0; i < words.size(); ++i)
            index[words[i]] = i;
        
        set<vector<int> > ans;
        for(string s : words) {
            int len = s.length();
            // 若该字符串为空字符,则本身为回文串的字符串可以与空字符串拼接
            if(len == 0) {
                for(string tmps : words) {
                    if(isPalin(tmps) && tmps != s) {
                        vector<int> tmpres1 = {index[tmps], index[s]};
                        vector<int> tmpres2 = {index[s], index[tmps]};
                        res.push_back(tmpres1);
                        res.push_back(tmpres2);
                    }
                }
                continue;
            }
            string tmp1 = "", tmp2 = "";
            // 寻找与该字符串的前缀和后缀拼接能构成回文串的字符串
            for(int i = 0; i < len; ++i) {
                tmp1.insert(0, 1, s[i]);
                tmp2 += s[len - i - 1];
                if(isPalin(s + tmp1) && index.find(tmp1) != index.end() && tmp1 != s) {
                    vector<int> tmpres = {index[s], index[tmp1]};
                    ans.insert(tmpres);
                }
                if(isPalin(tmp2 + s) && index.find(tmp2) != index.end() && tmp2 != s) {
                    vector<int> tmpres = {index[tmp2], index[s]};
                    ans.insert(tmpres);
                }
            }
        }
        
        for(auto iter = ans.begin(); iter != ans.end(); ++iter)
            res.push_back(*iter);
        
        return res;
    }
    // 判断该字符串是否是回文串
    bool isPalin(string s) {
        int len = s.length();
        for(int i = 0; i < len / 2; ++i) {
            if(s[i] != s[len - i - 1])
                return false;
        }
        return true;
    }
};

猜你喜欢

转载自www.cnblogs.com/heyn1/p/11209613.html