题目:
题解:
//字典树节点
class TrieNode
{
private:
bool isEnd;//单词结束标记
int index;//单词序号
vector<TrieNode*> children;//子节点
public:
//构造
TrieNode():index(-1),isEnd(false),children(26,nullptr){}
//析构
~TrieNode()
{
for(int i = 0;i < 26;i++)
{
if( children[i])
{
delete children[i];
children[i] = nullptr;
}
}
}
//对外接口
int getIndex() { return index;}
void setIndex( int i) { index = i;}
bool isWordEnd() { return isEnd;}
void SetEnd(){ isEnd = true ;}
//插入一个字符到子节点
TrieNode * insertNode(char c)
{
if( !( 'a' <= c <= 'z')) return nullptr;
int id = c-'a';
if( children[id] == nullptr)
{
children[id] = new TrieNode();
}
return children[id];
}
//在子节点中查找一个字符
TrieNode * getNode(char c)
{
if( !( 'a' <= c <= 'z')) return nullptr;
int id = c-'a';
return children[id] ;
}
};
//字典树
class Trie
{
private:
TrieNode * root;//根节点
public:
Trie():root(new TrieNode()){}
~Trie() { delete root;}
//插入一个单词及序号
void insert( string word,int index)
{
TrieNode * p = root;
for( int i = 0;i<word.size();i++)
{
p = p->insertNode(word[i]);
}
p->SetEnd();
p->setIndex(index);
}
//查找一个字符串
TrieNode *getNode(string word)
{
TrieNode * p = root;
for(int i = 0;i < word.size();i++ )
{
p = p->getNode(word[i]) ;
if( p == NULL ) return NULL;
}
return p;
}
//查找一个单词,返回序号
bool search(string word,int &index)
{
TrieNode * p = getNode(word);
if( p )
{
index = p->getIndex();
return p->isWordEnd();
}
return false;
}
};
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
//构建字典树
Trie * trieTree = new Trie();
for(int i = 0;i < words.size();i++)
{
trieTree->insert(words[i],i);
}
for(int i = 0;i < words.size();i++)
{
for(int j = 0;j < words[i].size();j++ )
{
bool flag = check(words[i],0,j);
if(flag)//前半截是回文
{
string temp = words[i].substr(j+1);
reverse(temp.begin(),temp.end());
int index = -1;
if( trieTree->search(temp,index) )
{
if( i != index )
{
res.push_back({index,i});
if( temp == "")
{
res.push_back({i,index});
}
}
}
}
flag = check(words[i],j+1,words[i].size()-1);
if(flag)//后半截是回文
{
string temp = words[i].substr(0,j+1);
reverse(temp.begin(),temp.end());
int index = -1;
if( trieTree->search(temp,index) )
{
if( i != index )
res.push_back({i,index});
}
}
}
}
return res;
}
bool check(string &vec,int left,int right)
{
int i = left;
int j = right;
while(i <= j)
{
if( vec[i] != vec[j]) return false;
i++;
j--;
}
return true;
}
};