1455. 检查单词是否为句中其他单词的前缀
题目:给你一个字符串 sentence 作为句子并指定检索词为 searchWord ,其中句子由若干用 单个空格 分隔的单词组成。请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。
如果 searchWord 是某一个单词的前缀,则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)。如果 searchWord 是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。如果 searchWord 不是任何单词的前缀,则返回 -1 。
字符串 s 的 前缀 是 s 的任何前导连续子字符串。
链接 https://leetcode.cn/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
个人思路
- 先使用split对句子切分为一个个单词,然后遍历每个单词是否以searchWord开头即可,如果没有就返回-1。注意这里下标是从1开始
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
wordList = sentence.split(' ')
length = len(wordList)
for i in range(length):
if wordList[i].startswith(searchWord):
return i+1
return -1
更python的写法:
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i, s in enumerate(sentence.split(" "), 1):
if s.startswith(searchWord):
return i
return -1
官方思路
- 双指针
使用 start 记录单词的起始,end 记录单词结尾的下一个位置。我们遍历字符串 sentence 并不断地分割单词,对于区间 (start,end) 对应的单词,判断它是否存在某一前缀等于 searchWord,如果存在直接返回该单词对应的下标 index;如果遍历完所有单词都不符合条件,返回 −1。
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
i, index, n = 0, 1, len(sentence)
while i < n:
start = i
while i < n and sentence[i] != ' ':
i += 1
end = i
if sentence[start:end].startswith(searchWord):
return index
index += 1
i += 1
return -1
参考:
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/solution/jian-cha-dan-ci-shi-fou-wei-ju-zhong-qi-pqpu2/