其实要排除列表中后缀相重合的字符,开始直接匹配后缀是否重合,超时了。
思路是先把单词反转过来,就变成了匹配前缀了,但是这样需要遍历两遍,那么不妨先排序,然后只需要比较相邻的两个字母。
class Solution(object):
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
reverseWord = []
for word in set(words):
reverseWord.append(word[::-1])
reverseWord.sort()
cur = ""
num = 0
for word in reverseWord + [""]:
if not word.startswith(cur):
num = num + len(cur) + 1
cur = word
return num
开始写的代码超时了,思路如下:
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
string s=words[0];
int num=s.length();
int len=words.size();
if(len==1) return num+1;
vector<string> res;
int book[3000];
memset(book,0,sizeof(book));
for(int i=0;i<len;i++){
bool flag=true;
for(int j=0;j<len;j++){
if(book[j]==1) continue;
if(i==j) continue;
int idx=words[j].find(words[i]);
int idx2=words[i].find(words[j]);
int len1=words[i].length();
int len2=words[j].length();
if(idx2!=string::npos&&idx2==len1-len2){
book[j]=1;
}
if(idx!=string::npos&&idx==len2-len1){ //找到后缀了
flag=false;
book[i]=1;
break;
}
}
if(flag) {res.push_back(words[i]);}
}
int sum=0;
for(int i=0;i<res.size();i++)
{
sum=res[i].size()+1+sum;
}
return sum;
}
};