[leetcode]820. Short Encoding of Words
Analysis
好冷鸭—— [每天刷题并不难0.0]
Given a list of words, we may encode it by writing a reference string S and a list of indexes A.
For example, if the list of words is [“time”, “me”, “bell”], we can write it as S = “time#bell#” and indexes = [0, 2, 5].
Then for each index, we will recover the word by reading from the reference string from that index until we reach a “#” character.
What is the length of the shortest reference string S possible that encodes the given words?
如果某个字符串是另一个字符串的后缀,则可以合并。先把每个字符串都翻转一下,然后再排序,最后判断每个字符串是否包含在其相邻字符串中就可以了。
Implement
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
int len = words.size();
for(int i=0; i<len; i++)
reverse(words[i].begin(), words[i].end());
sort(words.begin(), words.end());
vector<string> words1;
words1.push_back(words[len-1]);
string tmp = words[len-1];
for(int i=len-2; i>=0; i--){
if(tmp.find(words[i]) == string::npos){
tmp = words[i];
words1.push_back(tmp);
}
}
int res = 0;
for(auto word:words1)
res += word.size();
res += words1.size();
return res;
}
};
下面是大神的巧妙做法,就是先把整个输入存在hash表中,然后删掉所有前缀,最后剩下的就是shortcode
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
unordered_set<string> w(words.begin(), words.end());
for(string word:w){
for(int i=1; i<word.size(); i++)
w.erase(word.substr(i));
}
int res = 0;
for(string word:w)
res += word.size()+1;
return res;
}
};