# 1078. Occurrences After Bigram

Given words `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`.

For each such occurrence, add “`third`“ to the answer, and return the answer.

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"]
``````

Note:

1. `1 <= text.length <= 1000`
2. `text` consists of space separated words, where each word consists of lowercase English letters.
3. `1 <= first.length, second.length <= 10`
4. `first` and `second` consist of lowercase English letters.

``````class Solution {
public:
vector<string> findOcurrences(string text, string first, string second) {
vector<string> res, words;
istringstream iss(text);
string t;
while (iss >> t) {
int n = words.size();
if (n >= 2 && words.back() == second && words[n - 2] == first) res.push_back(t);
words.push_back(t);
}
return res;
}
};
``````

``````class Solution {
public:
vector<string> findOcurrences(string text, string first, string second) {
vector<string> res, words;
istringstream iss(text);
string t, pre, pre2;
while (iss >> t) {
if (pre2 == first && pre == second) res.push_back(t);
pre2 = pre;
pre = t;
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1078

https://leetcode.com/problems/occurrences-after-bigram/

https://leetcode.com/problems/occurrences-after-bigram/discuss/308385/C%2B%2B-stringstream

https://leetcode.com/problems/occurrences-after-bigram/discuss/308224/JavaPython-3-Split-String.

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation