Split the text and inspect each consecutive triple, emitting the third word when the first two match the bigram.
Complexity
O(n) time and O(n) token space.
Return every word that immediately follows a specified two-word sequence in text.
Split the text and inspect each consecutive triple, emitting the third word when the first two match the bigram.
O(n) time and O(n) token space.
package main
import "strings"
func findOcurrences(text string, first string, second string) []string {
words := strings.Fields(text)
result := []string{}
for index := 2; index < len(words); index++ {
if words[index-2] == first && words[index-1] == second {
result = append(result, words[index])
}
}
return result
}
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> list[str]:
words = text.split()
return [words[index] for index in range(2, len(words)) if words[index - 2] == first and words[index - 1] == second]
function findOcurrences(text: string, first: string, second: string): string[] {
const words = text.split(" "); const result: string[] = [];
for (let index = 2; index < words.length; index += 1) if (words[index - 2] === first && words[index - 1] === second) result.push(words[index]);
return result;
}