Bigram 分词:https://leetcode-cn.com/problems/occurrences-after-bigram/
思路:刚开始自己的想法是首先拼接first与second即string total = first + " “+second+” ";通过find函数对字符串total进行查找,若匹配到则从下一个字符开始到下一个空格为止,将其复制到字符数组中,并将母串中的第一个frist进行删除,然后循环进行直到字符串遍历完毕。
#pragma once
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
static vector<string> findOcurrences(string text, string first, string second) {
vector<string> v;
string total = first + " "+second+" ";
int x = 0;
int count = 0;
int begin = 0;
string end = "";
while (x=text.find(total)){
for (int i = x + total.length(); text[i] != ' '; i++) {
end+= text[i];
begin++;
}
cout << end;
v.push_back(end);
text.replace(x, first.length()+1,"");
cout << text;
count++;
begin = 0;
end = "";
}
return v;
}
};
但是发现对c++还不太熟悉,看了评论区之后改用java,依据其思想进行改变
class Solution {
public String[] findOcurrences(String text, String first, String second) {
String[] texts = text.split(" ");
ArrayList<String> result = new ArrayList<String>();
int x = 0;
for (int i = 0; i < texts.length; i++) {
if ((i+2)<texts.length&&texts[i].equals(first) && texts[i + 1].equals(second)) {
result.add(texts[i + 2]);
}
}
return result.toArray(new String[result.size()]);
}
}