1. 程式人生 > >[leetcode]820. Short Encoding of Words

[leetcode]820. Short Encoding of Words

[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;
    }
};