Leetcode 1455. Check whether the word is the prefix of other words in the sentence

Time:2021-1-26
  • Title Requirements:

Leetcode 1455. Check whether the word is the prefix of other words in the sentence
Leetcode 1455. Check whether the word is the prefix of other words in the sentence
Leetcode 1455. Check whether the word is the prefix of other words in the sentence

  • Thinking:

    • First, the string is divided into a list, and the separator is a space
    • Traverse this array, if the length of the current element is less than the given search term, directly traverse the next one
    • If the length of the current element is equal to or greater than the given search term, traverse the search term, and compare the element with the search term one by one. If it is inconsistent, break directly. If it is consistent, and the current subscript is the length of the search term – 1, indicating that the characters in front of the current word are the search term. Return the subscript + 1 of the word
    • Return – 1 at the end of traversal, indicating that there is no search term as prefix
  • Core code:
nums = sentence.split(" ")
for i in range(len(nums)):
    if len(nums[i]) >= len(searchWord):
        for j in range(len(searchWord)):
            if nums[i][j] == searchWord[j]:
                if j == len(searchWord) - 1:
                    return i + 1
            else:
                break
return -1
  • Full code:
class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        nums = sentence.split(" ")
        for i in range(len(nums)):
            if len(nums[i]) >= len(searchWord):
                for j in range(len(searchWord)):
                    if nums[i][j] == searchWord[j]:
                        if j == len(searchWord) - 1:
                            return i + 1
                    else:
                        break
        return -1

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]