LeetCode [820] The word of compression coding

topic

Given a list of words, this list will be encoded as a string S index and an index list A.
For example, if the list is [ "time", "me" , "bell"], we can be expressed as S = "time # bell #" and indexes = [0, 2, 5 ].
For each index, we can start by reading the string index from the string S in position until the "#" end, to restore our previous list of words.
Then the minimum length of the string to the success of a given word list for encoding is how much?

Example:

输入: words = ["time", "me", "bell"]
输出: 10
说明: S = "time#bell#" , indexes = [0, 2, 5] 。

prompt:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • Each word is lowercase.

A thought: storage suffix

All the words in the set, for set for each word, traversing the suffix to see if in the set, if it is removed, such as time, then traverse ime, me, e, delete me. This ensures that the set of words that can no longer left to the merger, plus the final set to traverse the length of each word and #.

Code

Time complexity: O ($ \ sum w_ { i} ^ 2 $), where $ w_ {i} $ is the words [i] of length, each word has $ w_ {i} $ suffix, which queries whether the hash value needs to be set O ($ w_ {i} $ ) is calculated.
Space complexity: O ($ \ sum w_ { i} $), the word storage space overhead.

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        int res = 0;
        unordered_set<string> ust(words.begin(), words.end());
        for (string word : ust) {
            for (int i = 1; i < word.size(); ++i) {
                ust.erase(word.substr(i));
            }            
        }
        for (string word : ust) {
            res += word.size() + 1;
        }
        return res;
    }
};

Guess you like

Origin www.cnblogs.com/galaxy-hao/p/12590041.html