1.题目
给出第一个词 first 和第二个词 second,考虑在某些文本 text 中可能以 "first second third" 形式出现的情况,其中 second 紧随 first 出现,third 紧随 second 出现。
对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。
示例 1:
输入:text = "alice is a good girl she is a good student", first = "a", second = "good" 输出:["girl","student"]
示例 2:
输入:text = "we will we will rock you", first = "we", second = "will" 输出:["we","rock"]
提示:
1 <= text.length <= 1000text由小写英文字母和空格组成text中的所有单词之间都由 单个空格字符 分隔1 <= first.length, second.length <= 10first和second由小写英文字母组成
2.解析
text(一个字符串,我们要在其中查找特定的字符串),first(第一个字符串)和second(第二个字符串)。这个函数的目标是在text中查找所有first和second的连续出现后的第三个词 "third" ,并返回这些第三个词 "third" 的列表。s=first + " " + second:定义一个字符串s,是first和second的连接,中间有一个空格。ls = re.findall("[a-z]*" + s + " " + "[a-z]+", text):使用正则表达式在text中查找所有以字母开头,接着是s,然后是一个或多个字母的组合。结果存储在列表ls中。ls1 = re.findall(s + " " + s + " " + "([a-z]+)", text):在文本中查找所有s连续出现两次,中间有一个空格和一个或多个字母的组合。结果存储在列表ls1中。if first==second::如果第一个和第二个字符串相同,则执行以下操作。ls1+=re.findall(second + " " + s + " " + "([a-z]+)",text):在文本中查找所有与之前相同的字符串(因为first和second相同),即查找所有连续出现两次的字符串,中间有一个空格和一个或多个字母的组合。找到的结果添加到ls1中。
3.python代码
class Solution:def findOcurrences(self, text: str, first: str, second: str) -> list[str]:import res=first + " " + secondls = re.findall("[a-z]*" + s + " " + "[a-z]+", text)ls1 = re.findall(s + " " + s + " " + "([a-z]+)", text)if first==second:ls1+=re.findall(second + " " + s + " " + "([a-z]+)",text)for x in ls:if x.startswith(s):ls1 += re.findall(s + " " + "([a-z]+)", x)return ls1
4.运行结果