leetcode820单词的压缩缩码java题解(子串删除)

1.题目
给定一个单词列表,我们将这个列表编码成一个索引字符串 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
2.想法
将每个位置的字符串与其他位置的字符串进行比较,若字符串包含其他字符串且其他字符串为其后缀(这一点要注意,abcd与bc并不能删除bc,要abc与bc才能删除bc,清楚这一点第27个样例才可以过),然后再循环一遍数组统计一共多长
3.自己题解

class Solution {
    
    
    public int minimumLengthEncoding(String[] words) {
    
    
      //Arrays.sort(words);
      int length=0;     
      for(int i=0;i<words.length;i++){
    
    
        //String temp=words[i];        
        if(words[i]!=null){
    
    
        for(int j=0;j<words.length;j++){
    
              
          if(words[j]!=null&&
          words[j].length()<=words[i].length()&&
          i!=j&&
          (words[i].indexOf(words[j]))!=-1&&words[i].indexOf(words[j])+words[j].length()==words[i].length()){
    
    
            words[j]=null;}
            }          
        }}
        for(int i=0;i<words.length;i++){
    
    
          if(words[i]!=null)length+=words[i].length()+1;
        }
    return length;
      }   
    }

4.效率
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zeshen123/article/details/105159276