LeetCode 1455. 检查单词是否为句中其他单词的前缀

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/

个人思路
  1. 先使用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
官方思路
  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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值