题目传送门
思路一:暴力,将字符串按字符个数从大到小排列,然后判断后续字符串是否是匹配字符串的子串。
class Solution
{
public:
int minimumLengthEncoding(vector<string>& words)
{
string str="";
int lengths=words.size();
priority_queue<pair<int,int> > pq;
for(int i=0;i<lengths;i++)
{
int templength=words[i].length();
pq.push(make_pair(templength,i));
}
while(!pq.empty())
{
string tempstr=words[pq.top().second];
tempstr+="#";
pq.pop();
if(str.find(tempstr)==string::npos)
{
str+=tempstr;
}
}
return str.length();
}
};
思路二:字典树(注意现在其实是字符串的倒序匹配)
class Treenode
{
public:
Treenode* children[26];
Treenode()
{
for(int i=0;i<26;i++)
{
children[i]=NULL;
}
}
};
class Tri
{
public:
Treenode* root;
Tri()
{
root=new Treenode();
}
int insertstr(string s)
{
Treenode* tnode=root;
bool isnew=false;
int strlength=s.length();
for(int i=strlength-1;i>=0;i--)
{
int index=int(s[i]-'a');
if(tnode->children[index]==NULL)
{
isnew=true;
tnode->children[index]=new Treenode();
}
tnode=tnode->children[index];
}
if(isnew)
{
return strlength+1;
}
else
{
return 0;
}
}
};
class Solution
{
public:
int minimumLengthEncoding(vector<string>& words)
{
int re=0;
int lengths=words.size();
priority_queue<pair<int,int> > pq;
for(int i=0;i<lengths;i++)
{
int templength=words[i].length();
pq.push(make_pair(templength,i));
}
Tri* t=new Tri();
while(!pq.empty())
{
string tempstr=words[pq.top().second];
re=re+t->insertstr(tempstr);
pq.pop();
}
return re;
}
};