给出第一个词 first 和第二个词 second,考虑在某些文本 text 中可能以 "first second third" 形式出现的情况,其中 second 紧随 first 出现,third 紧随 second 出现。
对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。
输入:text = "alice is a good girl she is a good student", first = "a", second = "good" 输出:["girl","student"]
解题思路:没啥好说的,又是istringstream的应用,利用istringstream把string字符串按空格分为各个string,然后暴力枚举
class Solution {
public:
vector<string> findOcurrences(string text, string first, string second) {
istringstream words(text);
string w;
vector<string> tmp, ans;
while (words >> w) tmp.push_back(w);
for (int i = 0, j = 1; j < tmp.size() - 1; ++i, ++j)
if (tmp[i] == first && tmp[j] == second) ans.push_back(tmp[j + 1]);
return ans;
}
};