解题思路
由于C++并没有像java那样直接调用split函数对每个单词进行分割,所以遍历分割的话会很麻烦,这里我想到了string数据结构有find函数,那么我只要把目标的first和second组合起来,用find找到其位置,然后把字符串后面的单词放入res数组中即可。实现起来有一个小细节,就是通过用例发现first可能是其中某个单词的一部分,这就不符合要求了,所以要判断每次找到的position所在的单词是不是first,代码如下:
代码
class Solution {
public:
vector<string> findOcurrences(string text, string first, string second) {
vector<string> res;
// 目标字符串
string target = first + ' ' + second + ' ';
int len = target.size();
int pos = 0;
while((pos = text.find(target, pos)) != string::npos) {
// 判断是否是隔开的字母
if(pos == 0 || text[pos - 1] == ' ') {
int i = pos + len;
string temp;
while(i < text.size() && text[i] != ' ') {
temp += text[i ++];
}
res.push_back(temp);
}
pos += 1;
}
return res;
}
};