LeetCode 39. word of compression coding

Title Description

Given a list of words, this list will be encoded as a string S index and an index list A.

For example, if the list is [ "time", "me", "bell"], we can be expressed as S = "time # bell #" and indexes = [0, 2, 5].

For each index, we can start by reading the string index from the string S in position until the "#" end, to restore our previous list of words.

Then the minimum length of the string to the success of a given word list for encoding is how much?

 

Example:

Input: words = [ "time", "me", "bell"]
Output: 10
Description: S = "time # bell # ", indexes = [0, 2, 5].
 

prompt:

. 1 <= words.length <= 2000
. 1 <= words [I] .length <=. 7
each word lowercase.

Problem-solving ideas

The length of each word according to the descending order,

Then traverse the entire array encounters a word word, judge stringbuilder there is no word # this field, if not, add this field stringbuilder

Back to the length stringbuilder

code show as below

package leetcode;

import java.util.Arrays;

public class MinimumLengthEncoding {
      public int minimumLengthEncoding(String[] words) {
        
          Arrays.sort(words,(String word1,String word2)->word2.length()-word1.length());
          StringBuilder sb=new StringBuilder();
          sb.append(words[0]+"#");
          for (int i = 0; i < words.length; i++) {
            if (sb.indexOf(words[i]+"#")==-1) {
                sb.append(words[i]+"#");
            }
        }
          return sb.length();

        }
}

 

Guess you like

Origin www.cnblogs.com/Transkai/p/12586745.html