[编程题]3
  • 热度指数:394 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

给定英文句子S和字符串x,判断x是否为S中某些单词的前缀,若匹配到则输出第1个匹配单词的位置,否则输出-1

例如:输入"this is an easy problem.""eas",输出4

例如:输入"In love folly is always sweet""like",输出-1

例如:输入"Whatever is worth doing is worth doing well.""wor",输出3


示例1

输入

"this is an easy problem.","eas"

输出

4
#
# 在句子中找到前缀是str的首个单词位置
# @param s string字符串 英文句子
# @param x string字符串 字符串
# @return int整型
#
class Solution:
    def match_str_in_sentence(self , s , x ):
        # write code here
        if s=="":return -1
        ss=s.split(' ')
        for i in range(len(ss)):
            if ss[i].find(x)!=-1:
                return (i+1)
        return -1

发表于 2021-06-02 19:28:04 回复(0)
class Solution:
    def match_str_in_sentence(self , s , x ):
        # write code here、
        strs = s.split()
        count = 0
        for s in strs:
            count += 1
            if len(s) < len(x):
                continue
            else:
                if s[:len(x)] == x:
                    return count
                else:
                    continue
        return -1

编辑于 2021-04-18 21:10:19 回复(0)