leetcode解题之单词的压缩编码

给定一个单词列表,我们将这个列表编码成一个索引字符串 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
每个单词都是小写字母 。

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

个人的思路是先按单词的长度降序排列,然后再比较相邻单词的是否存在大包小的情况

class Solution {
    public int minimumLengthEncoding(String[] words) {  
        //按长度降序
        Arrays.sort(words,(s1,s2)->s2.length()-s1.length());
        String temS = "";
        for(String word:words){
            String str=word+"#";//组合编码
            if(temS.indexOf(str)>-1){
                continue;
            }
            temS+=str;
        
        }
        return temS.length();
    }
}

学习记录一下经典的前缀树(tire树)的解法

class Solution {
     //trie树
    public int minimumLengthEncoding(String[] words) {  
        //长度倒序
      Arrays.sort(words,(s1,s2)->{return s2.length()-s1.length();});
      int ans=0;
      Trie trie = new Trie();
        for(String word:words){
            ans+=trie.insert(word);
        }
       return ans;
    }
}
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];
     }
     return isNew?word.length()+1:0;
 }
}
class TrieNode{
    char val;
    TrieNode[] children = new TrieNode[26];//26个字母
    public TrieNode(){};
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值