Palindrome Pairs (第九周 字符串)

来源:互联网 发布:如何描述淘宝店铺 编辑:程序博客网 时间:2024/06/06 09:31

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. ote: m and n will be at most 100.

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

算法思路

(1)题目是给定一些字符串,求字符串两两组合的方法,使得结果是回文串。
(2)我们先定义判断一个字符串是否是回文串的函数,首先,我们用两个指针分别指向字符串的头部和尾部,如果指向的字符都相同,首指针就向后移动一格,尾指针就向前移动一格。如果指向的字符都不相同,直接返回结果,不是回文串。
(3)我们先定义一个字典(string,index)。对于每个单词,从左到右遍历一遍,对于任意一个位置,如果它的左边是回文串且右边的逆序在字典中出现,那么就存在这么一种组合,同理,如果它的右边是回文串且左边的逆序在字典中出现,那么也存在这么一种组合。

算法代码

class Solution {public:    bool isPalindrome(string s) {          int left = 0, right = s.length()-1;          while (left < right) {              if (s[left] != s[right])                  return false;              left++;              right--;          }          return true;      }     vector<vector<int> > palindromePairs(vector<string>& words) {        vector<vector<int> > res;        map<string,int> dic;          int sz = words.size();          for (int i = 0; i < sz; i++)              dic[words[i]] = i;         for (int i = 0; i < sz; i++){            int len = words[i].length();            for (int j = 0; j <= len; j++){                string subL = words[i].substr(0,j);                string subR = words[i].substr(j);                string revL;                revL = revL.assign(subL.rbegin(),subL.rend());                string revR;                revR = revR.assign(subR.rbegin(),subR.rend());                if (j != len && isPalindrome(subR) && dic.count(revL)){                    if(i != dic[revL]){                        vector<int> tmp;                        tmp.push_back(i);                        tmp.push_back(dic[revL]);                        res.push_back(tmp);                    }                }                   if (isPalindrome(subL) && dic.count(revR)){                    if(i != dic[revR]){                        vector<int> tmp;                        tmp.push_back(dic[revR]);                        tmp.push_back(i);                        res.push_back(tmp);                    }                }               }        }        return res;    }};
0 0