820. 单词的压缩编码

给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。

例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0, 2, 5]。

对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。

那么成功对给定单词列表进行编码的最小字符串长度是多少呢?

 

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/short-encoding-of-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

方法

class Solution {
public:
    static bool cmp(string& s1, string& s2) {   
        return s1.size() > s2.size();
    }
    
    int minimumLengthEncoding(vector<string>& words) {
        sort(words.begin(), words.end(), cmp);    // key1:排序
        
        string ret = "";                          
        for (auto word : words) {
            int found = ret.find(word);           // key3:使用str.find来查找子串
            if (found == string::npos || ret[found + word.size()] != '#') { 
                ret = ret + word + '#';
            }
        }
        return ret.size();
    }
};

  

分解:

1、把字符串按照长度排序

2、判断一个短串是否是一个长串的结尾子串

      如果是就不需要写入到结果里;

      如果不是就 “#” 然后写到结果里

 

这道题,在查找子串的时候,用的很巧妙的方法来判断是不是一个长串的结尾子串。

posted @ 2020-03-07 17:35  ren_zhg1992  阅读(323)  评论(0)    收藏  举报