[Power button - small daily practice] 820. The word compression coding (python)

820. The word compression coding

Topic links: https://leetcode-cn.com/problems/short-encoding-of-words/
Difficulty: Medium

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 index from the string S in position to start reading the string 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?

Examples

Input: words = [ "Time", "Me", "Bell"]
Output: 10
Description: S = "Bell Time # #", Indexes = [0, 2,. 5].

prompt

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • Each word is lowercase.

The sample code

I wrote methods, particularly violence, in short, is to be sorted in descending order according to the length of the word, and then by comparing the letters of a word-by, the function can be achieved, but it takes too long, exceeds the limit.
Is given below with reference to others, the idea is the same
violent problem solving: words according to the word length of the sort, from long to short word length traversal, if the target string can be completely read the word, the word is discarded
completely read: the presence of the word substrings, and "#" at the end
function

  • the list.sort (CMP = None, Key = None, Reverse = False)
    CMP - optional parameters, the parameter sorting method
    key - Sort, only one parameter
    reverse - collation, default False (ascending)

  • str.find (str1, the begin, End)
    str1 - substrings
    begin: end - Look
    if str1 in str, return str1 index; if not in, -1

The following is a reference to someone else

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        words.sort(key = lambda x: len(x))          #按单词长度排序
        ans = ''                                    #目标字符串
        for i in range(len(words)-1, -1, -1):       #按单词长度从长到短遍历(逆序循环)
            tmp = ans.find(words[i])                #单词是否在目标字符串中,若存在,返回索引
            if tmp == -1:                           #单词不在目标字符串中,添加进去
                ans += words[i] + '#'
            else:                                   #单词在目标字符串中,判断能否完全读取
                x = ans[tmp:].index('#')            #获取单词后第一个“#”索引
                if ans[tmp:tmp+x] != words[i]:      #判断是否能够完全读取,若不能,添加单词
                    ans += words[i] + '#'
        return len(ans)                             #返回目标字符串长度

#参考自:
#作者:pumpkin_daytoy
#链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/python3-bao-li-qiu-jie-by-pumpkin_daytoy/

The following is my own writing (takes too much time beyond the limit)

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        #'''
        S = ''
        if len(words)==1:
            return len(words[0])+1
       

        for k in range(len(words)):
            for t in range(len(words))[k:]:
                if len(words[k])<len(words[t]):
                    temp = words[t]
                    words[t] = words[k]
                    words[k] = temp
        S = words[0] + '#'    
        indexes = [0]
        for word in words[1:]:
            i = 0
            flag = False
            j = 0
            while True:
                char = word[j]
                if char == S[i]:
                    if j == 0:
                        flag = True
                    i += 1
                    j += 1
                else:
                    if S[i] != word[0]:
                        i += 1
                    if flag == True:
                        j = 0
                        flag = False
                        # break
                if j == len(word):
                    if i <= len(S)-1:
                        indexes.append(i-j)
                        break
                elif j < len(word) and i == len(S)-1:
                    S = S + word + '#'
                    break
                # if j == len(word) or i == len(S):
                #     break
        return len(S)
        #'''
Published 44 original articles · won praise 5 · Views 4462

Guess you like

Origin blog.csdn.net/ljb0077/article/details/105160171