Leetcode One Question of the Day 2021/01/09

[One question per day] Leetcode: 524. Match the longest word in the dictionary by deleting letters

  • Given a string and a string dictionary, find the longest string in the dictionary, which can be obtained by deleting some characters of the given string. If there is more than one answer, return the longest string with the smallest lexicographical order. If the answer does not exist, an empty string is returned.
  • Example 1:
输入:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
输出: 
"apple"
  • Example 2:
输入:
s = "abpcplea", d = ["a","b","c"]
输出: 
"a"
  • Explanation:
    1. All input strings only contain lowercase letters.
    2. The size of the dictionary will not exceed 1000.
    3. The length of all input strings will not exceed 1000.

  • My thinking:
    1
    Two problems encountered:
    1.
    2
    Understanding:
    3
    2.
    4
    Understanding:
    5
    Code:

class Solution:
    def findLongestWord(self, s: str, d: List[str]) -> str:
        dLen = len(d)
        index, indexlen, flag = 0, 0, 0    # flag是判断有无匹配的标志
        for i in range(dLen):
            strLen = len(d[i])
            cur = 0
            for j in s:
                if(d[i][cur] == j):
                    cur += 1
                if(cur == strLen):
                    flag = 1
                    if(indexlen < strLen or (indexlen == strLen and d[index] > d[i])):
                        index = i
                        indexlen = strLen
                    break
        if(flag == 1):
            return d[index]
        return ""

6

  • Optimization
    7
    code:
class Solution:
    def findLongestWord(self, s: str, d: List[str]) -> str:
        d.sort(key = lambda x: (-len(x), x))
        for word in d:
            index = 0
            for ch in word:
                index = s.find(ch, index)  # find输出-1:False
                if(index == -1):
                    break
                else:
                    index += 1  # 从下一个位置继续查
            else: 			    # break结束不会执行,正常结束会执行
                return word
        return ''

8

analysis:
9

  • New knowledge:
    Python's find() function:
    used to find whether the string contains the corresponding substring.
    10

Guess you like

Origin blog.csdn.net/weixin_40910614/article/details/112388584