second, consider occurrences in some
text of the form “
first second third“, where
second comes immediately after
third comes immediately after
For each such occurrence, add “
third” to the answer, and return the answer.
Input: text = "alice is a good girl she is a good student", first = "a", second = "good" Output: ["girl","student"]
Input: text = "we will we will rock you", first = "we", second = "will" Output: ["we","rock"]
1 <= text.length <= 1000
textconsists of space separated words, where each word consists of lowercase English letters.
1 <= first.length, second.length <= 10
secondconsist of lowercase English letters.
We can convert text to a list of words and search the “second” string in the list. If we find the “second” string in the list, we can check if the previous word in the list is the “first” string, if it is, we add the next word after the “second” string. Keep searching, until no more text words.
class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: results =  text_words = text.split() while second in text_words: second_index = text_words.index(second) if second_index > 0 and second_index < len(text_words) - 1 and text_words[second_index - 1] == first: results.append(text_words[second_index + 1]) text_words = text_words[second_index + 1:] return results
- Time Complexity: O(N).
- Space Complexity: O(N).