Leetcode.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] 。
 

提示:

1 <= words.length <= 2000
1 <= words[i].length <= 7
每个单词都是小写字母 。

思路

只要某个单词可以作为另一单词的后缀,则可以减少其字符串大小的编码长度。每次取出一个字符串与剩下的字符串进行比对,看是否可以成为剩下字符串的后缀,时间复杂度为O(n^2*c),c为字符串最大长度,题目中规定为7,勉强能通过所有测试用例。

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        int p=0, n=0, s=words.size();
        vector<int> merged(words.size(), 0);
        for(int i=0; i<words.size(); i++){
            p+=words[i].size();
            for(int j=0; j<words.size(); j++){
                if(j==i || merged[j])    continue;
                if(func(words[i], words[j])){
                    n-=words[i].size();
                    s--;
                    merged[i]=1;
                    break;
                }
            }
        }
        return p+n+s;
    }
    bool func(string& str1, string& str2){//比对 str1 是否能成为 str2 的后缀
        if(str1.size()>str2.size())
            return false;
        int p1=str1.size();
        int p2=str2.size();
        while(p1--){
            if(str1[p1]!=str2[--p2])
                return false;
        }
        return true;
    }
};

在评论区看到大神甜姨Sweetiee的用单词树方法题解,整体复杂度只需O(n*c),即遍历一遍所有字符串。搬运一下大神的代码,方便日后自己复习巩固:

class Solution {
    public int minimumLengthEncoding(String[] words) {
        int len = 0;
        Trie trie = new Trie();
        // 先对单词列表根据单词长度由长到短排序
        Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
        // 单词插入trie,返回该单词增加的编码长度
        for (String word: words) {
            len += trie.insert(word);
        }
        return len;
    }
}

// 定义tire
class Trie {
    
    TrieNode root;
    
    public Trie() {
        root = new TrieNode();
    }

    public int insert(String word) {
        TrieNode cur = root;
        boolean isNew = false;
        // 倒着插入单词
        for (int i = word.length() - 1; i >= 0; i--) {
            int c = word.charAt(i) - 'a';
            if (cur.children[c] == null) {
                isNew = true; // 是新单词
                cur.children[c] = new TrieNode();
            }
            cur = cur.children[c];
        }
        // 如果是新单词的话编码长度增加新单词的长度+1,否则不变。
        return isNew? word.length() + 1: 0;
    }
}

class TrieNode {
    char val;
    TrieNode[] children = new TrieNode[26];

    public TrieNode() {}
}
发布了18 篇原创文章 · 获赞 0 · 访问量 773

猜你喜欢

转载自blog.csdn.net/afiguresomething/article/details/105174406