3月打卡活动第28天 LeetCode第820题:单词的压缩(中等)

3月打卡活动第28天 LeetCode第820题:单词的压缩(中等)

  • 题目:给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。例如,如果这个列表是 [“time”, “me”, “bell”],我们就可以将其表示为 S = “time#bell#” 和 indexes = [0, 2, 5]。对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
    在这里插入图片描述
  • 解题思路:用到了一个不常用的函数,SS.indexOf(ss),判断SS中是否包含ss,包含返回起始位置,不包含返回-1。
class Solution {
    public int minimumLengthEncoding(String[] words) {
        String S = "";
        int len = words.length;
        S += words[0]+"#";
        for(int i=1;i<len;i++){
            String ss = words[i]+"#";
            if(S.indexOf(ss)==-1){
                S += ss;
            }
        }
        String SS = "";
        SS += words[len-1]+"#";
        for(int i=len-2;i>=0;i--){
            String ss = words[i]+"#";
            if(SS.indexOf(ss)==-1){
                SS += ss;
            }
        } 
        return Math.min(S.length(),SS.length());
    }
}

在这里插入图片描述

  • 题解做法1:记录单词后缀。
class Solution {
    public int minimumLengthEncoding(String[] words) {
        Set<String> good = new HashSet(Arrays.asList(words));
        for (String word: words) {
            for (int k = 1; k < word.length(); ++k)
                good.remove(word.substring(k));
        }

        int ans = 0;
        for (String word: good)
            ans += word.length() + 1;
        return ans;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

  • 解题做法2:字典树方法。
class Solution {
    public int minimumLengthEncoding(String[] words) {
        TrieNode trie = new TrieNode();
        Map<TrieNode, Integer> nodes = new HashMap();

        for (int i = 0; i < words.length; ++i) {
            String word = words[i];
            TrieNode cur = trie;
            for (int j = word.length() - 1; j >= 0; --j)
                cur = cur.get(word.charAt(j));
            nodes.put(cur, i);
        }

        int ans = 0;
        for (TrieNode node: nodes.keySet()) {
            if (node.count == 0)
                ans += words[nodes.get(node)].length() + 1;
        }
        return ans;

    }
}

class TrieNode {
    TrieNode[] children;
    int count;
    TrieNode() {
        children = new TrieNode[26];
        count = 0;
    }
    public TrieNode get(char c) {
        if (children[c - 'a'] == null) {
            children[c - 'a'] = new TrieNode();
            count++;
        }
        return children[c - 'a'];
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了111 篇原创文章 · 获赞 17 · 访问量 2910

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/105155719
今日推荐