Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after
first, and third comes immediately after second.
Return an array of all the wordsthirdfor each occurrence of"first second third".
We want to find all words that come immediately after a given bigram (pair of words). By sliding a window of size 3 over the words, we can check if the first two match the bigram and collect the third.
classSolution {
public String[]findOcurrences(String text, String first, String second) {
String[] words = text.split(" ");
List<String> ans =new ArrayList<>();
for (int i = 2; i < words.length; i++) {
if (words[i-2].equals(first) && words[i-1].equals(second))
ans.add(words[i]);
}
return ans.toArray(new String[0]);
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindOcurrences(text: String, first: String, second: String): Array<String> {
val words = text.split(" ")
val ans = mutableListOf<String>()
for (i in2 until words.size) {
if (words[i-2] == first && words[i-1] == second)
ans.add(words[i])
}
return ans.toTypedArray()
}
}
1
2
3
4
5
6
7
8
classSolution:
deffindOcurrences(self, text: str, first: str, second: str) -> list[str]:
words = text.split()
ans = []
for i in range(2, len(words)):
if words[i-2] == first and words[i-1] == second:
ans.append(words[i])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnfind_ocurrences(text: String, first: String, second: String) -> Vec<String> {
let words: Vec<&str>= text.split_whitespace().collect();
letmut ans = Vec::new();
for i in2..words.len() {
if words[i-2] == first && words[i-1] == second {
ans.push(words[i].to_string());
}
}
ans
}
}