题目
给你一个字符串 sentence
作为句子并指定检索词为 searchWord
,其中句子由若干用 单个空格 分隔的单词组成。请你检查检索词 searchWord
是否为句子 sentence
中任意单词的前缀。
如果 searchWord
是某一个单词的前缀,则返回句子 sentence
中该单词所对应的下标(下标从 1 开始)。如果 searchWord
是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。如果 searchWord
不是任何单词的前缀,则返回 -1
。
字符串 s
的 前缀 是 s
的任何前导连续子字符串。
示例 1:
输入:sentence = "i love eating burger", searchWord = "burg"
输出:4
解释:"burg" 是 "burger" 的前缀,而 "burger" 是句子中第 4 个单词。
示例 2:
输入:sentence = "this problem is an easy problem", searchWord = "pro"
输出:2
解释:"pro" 是 "problem" 的前缀,而 "problem" 是句子中第 2 个也是第 6 个单词,但是应该返回最小下标 2 。
示例 3:
输入:sentence = "i am tired", searchWord = "you"
输出:-1
解释:"you" 不是句子中任何单词的前缀。
提示:
1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence
由小写英文字母和空格组成。searchWord
由小写英文字母组成。
题解1
思路
- 将字符串按空格进行分隔,对分隔后的每一个子串判断其前缀是否为目标值
- 若是则返回索引+1
- 若无,则返回-1
代码
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
ret = -1
words = sentence.split(" ")
for i in range(len(words)-1, -1, -1):
if words[i].startswith(searchWord):
ret = i+1
return ret
复杂度
- 时间复杂度: O ( m n ) O(mn) O(mn) m m m为目标前缀的长度, n n n为字符串长度
- 空间复杂度: O ( n ) O(n) O(n)
题解2
思路
- 遍历字符串,每遇到一个新的单词就判断其前缀是否为目标值
- 若是,则直接返回当前的循环次数
- 若不是,则跳过当前单词和空格,遍历下一个单词
代码
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
i = 0
count = 1
while i < len(sentence):
j = 0
while i<len(sentence) and sentence[i] != " " and j<len(searchWord) and sentence[i] == searchWord[j]:
i,j = i+1, j+1
if j == len(searchWord): return count
while i<len(sentence) and sentence[i] != " ": i+=1
while i<len(sentence) and sentence[i] == " ": i+=1
count += 1
return -1
复杂度
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)