Leetcode 1078. Occurrences After Bigram
Given two strings first
and second
, consider all the occurrences of the first and second words appearing one after the other in the text. Return the list of words that appear immediately after the sequence of first
and second
.
Example 1:
Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl", "student"]
Example 2:
Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we", "rock"]
Constraints:
first
, second
).text
is between 1 and 1000.text
, first
, and second
are all lowercase?
A: Yes.text
only be composed of alphabetic characters?
A: Yes.To solve the problem, we can follow these steps:
text
into individual words using space as the delimiter.first
followed by second
.second
word, if it exists.#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
vector<string> findOcurrences(string text, string first, string second) {
vector<string> result;
vector<string> words;
stringstream ss(text);
string word;
// Split the input text into words
while (ss >> word) {
words.push_back(word);
}
// Iterate through the words and find occurrences of first and second followed by another word
for (int i = 0; i < words.size() - 2; ++i) {
if (words[i] == first && words[i + 1] == second) {
result.push_back(words[i + 2]);
}
}
return result;
}
int main() {
// Example 1
string text1 = "alice is a good girl she is a good student";
string first1 = "a";
string second1 = "good";
vector<string> result1 = findOcurrences(text1, first1, second1);
for (const string &word : result1) {
cout << word << " ";
}
cout << endl;
// Example 2
string text2 = "we will we will rock you";
string first2 = "we";
string second2 = "will";
vector<string> result2 = findOcurrences(text2, first2, second2);
for (const string &word : result2) {
cout << word << " ";
}
cout << endl;
return 0;
}
This solution processes the input efficiently and meets the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?