返回

一文读懂LeetCode 748:轻松补齐不完整单词,实现字符串精准匹配

闲谈

算法简介

LeetCode 748:最短补全词

在LeetCode 748中,您将面对一个有趣的字符串匹配问题。给定一个部分单词,您的任务是找到最短的单词,将其添加到部分单词之后,可以形成一个完整的单词。例如,如果给定部分单词是"app",那么"apple"、"append"和"application"都是有效的补全词。而其中最短的补全词是"apple",长度为5个字母。

解题思路

为了解决这个问题,我们需要采用以下步骤:

  1. 首先,我们将给定的部分单词保存在一个变量中,并将其长度存储在另一个变量中。
  2. 接着,我们将遍历给定的单词列表,并对每个单词执行以下操作:
    • 检查单词的长度是否大于或等于部分单词的长度。
    • 如果单词的长度大于或等于部分单词的长度,则将其与部分单词进行比较。
    • 如果单词与部分单词的前缀相同,则将其添加到一个候选补全词列表中。
  3. 最后,我们将在候选补全词列表中找到最短的单词,并将其作为补全词返回。

示例

以下是一个Python示例,演示如何解决LeetCode 748:

def shortest_completing_word(partial_word, words):
  """
  Finds the shortest word that can be added to the partial word to form a complete word.

  Args:
    partial_word: The partial word to be completed.
    words: A list of words to search for the shortest completing word.

  Returns:
    The shortest word that can be added to the partial word to form a complete word.
  """

  # Store the partial word and its length.
  partial_word_length = len(partial_word)

  # Create a list to store the candidate completing words.
  candidate_completing_words = []

  # Iterate over the given words.
  for word in words:
    # Check if the word's length is greater than or equal to the partial word's length.
    if len(word) >= partial_word_length:
      # Check if the word starts with the partial word.
      if word.startswith(partial_word):
        # Add the word to the candidate completing words list.
        candidate_completing_words.append(word)

  # Find the shortest word in the candidate completing words list.
  shortest_completing_word = min(candidate_completing_words, key=len)

  # Return the shortest completing word.
  return shortest_completing_word


# Test the function.
partial_word = "app"
words = ["apple", "append", "application", "approve", "arrival"]
shortest_completing_word = shortest_completing_word(partial_word, words)
print(shortest_completing_word)

输出结果:

apple