[LeetCode] 820. Short Encoding of Words

题:https://leetcode.com/problems/short-encoding-of-words/

题目大意

参考题目

思路

set 集合

将所有word 放入set中,然后遍历所有set中的word,将word的从头的子串都从set中删除,最后统计 set中所有(word 的长度 + 1)(’#’)

class Solution {
    public int minimumLengthEncoding(String[] words) {
        Set<String> set = new HashSet(Arrays.asList(words));
        for(String word : words){
            for(int i = 1 ; i <word.length();i++){
                set.remove(word.substring(i));
            }
        }
        int res = 0;
        for(String word:set){
            res += word.length() +1;
        }
        return res;
    }
}

trie

将word翻转 插入 trie中。
最后统计tire 中所有 叶子的深度 + 1 (’#’)

class TrieNode{
    char ch;
    boolean isLeaf;
    TrieNode []nextNode = new TrieNode[26];

    public TrieNode(char cCh){
        ch = cCh;
    }
}
class Trie{
    TrieNode root;

    public Trie(){
        root = new TrieNode('?');
    }
    public void insert(String s){
        TrieNode curNode = root;
        for(int  i = 0 ; i < s.length();i++){
            if(curNode.nextNode[s.charAt(i)-'a'] == null)
                curNode.nextNode[s.charAt(i)-'a'] = new TrieNode(s.charAt(i));
            curNode = curNode.nextNode[s.charAt(i)-'a'];
        }
        curNode.isLeaf = true;
    }
}
class Solution {
    int res = 0;
    public int minimumLengthEncoding(String[] words) {
        Trie trie = new Trie();
        for(String word:words){
            trie.insert((new StringBuilder(word)).reverse().toString());
        }
        calStringLen(trie.root,0);
        return res;
    }
    public void  calStringLen(TrieNode root,int level){
        if(root == null)
            return;

        boolean isTreeLeaf = true;
        for(int  i = 0 ; i < 26 ;i++){
            if(root.nextNode[i] != null){
                calStringLen(root.nextNode[i],level+1);
                isTreeLeaf = false;
            }
        }
        if(isTreeLeaf)
            res+=level+1;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值