- 题目要求:
-
思路:
- 先将字符串分割为列表,分隔符为空格
- 遍历这个数组,如果当前的元素长度小于给定的检索词,直接遍历下一个
- 如果当前的元素长度等于或大于给定的检索词,遍历检索词,把这个元素和检索词逐个对比,如果不一致,直接 break,如果一致,且当前的下标为检索词长度 -1,说明当前的这个单词前面的几个字符正是检索词,返回这个单词的下标 +1
- 遍历结束返回 -1,说明没有检索词作为前缀
- 核心代码:
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
- 完整代码:
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