LeetCode题解——Palindrome Pairs

来源:互联网 发布:找女朋友的软件 编辑:程序博客网 时间:2024/06/05 20:10

题目:

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

解题思路:

给定一个words,如何计算它可能的回文字符串。
将worsd[i]分为两部分,一部分是left,一部分是right,当right是回文串,并且left的revers words[j]在字典中存在时,那么此时[i,j]构成回文串。
同样的道理,当left是回文串,并且right的revers word[j] 在字典中存在时,那么此时[j,i]构成回文串。

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.

class Solution {public:    vector<vector<int>> palindromePairs(vector<string>& words) {        //给定一个words,如何计算它可能的回文字符串。        //将worsd[i]分为两部分,一部分是left,一部分是right,当right是回文串,并且left的revers words[j]在字典中存在时,那么此时[i,j]构成回文串        //同样的道理,当left是回文串,并且right的revers word[j] 在字典中存在时,那么此时[j,i]构成回文串        vector<vector<int>> res;        map<string,int> imap;        string temp;        for(int i=0; i<words.size(); i++){            temp = words[i];            reverse(temp.begin(),temp.end());            imap[temp] = i;        }                string left,right;            for(int i=0; i<words.size(); i++){            for(int j=0; j<words[i].size(); j++){                left = words[i].substr(0,j);                right = words[i].substr(j);                if(imap.find(left)!=imap.end() && imap[left]!=i && ispalindrome(right)){                    res.push_back({i,imap[left]});                     if(j==0) res.push_back({imap[left],i});                }                if(imap.find(right)!=imap.end() && imap[right]!=i && ispalindrome(left)){                    res.push_back({imap[right],i});                }            }        }                return res;    }     bool ispalindrome(string& s){         int sz = s.size();         for(int i=0; i<sz/2; i++){             if(s[i]!=s[sz-i-1]) return false;         }         return true;     }};



0 0
原创粉丝点击