题目:Bigram 分词
给出第一个词 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"]
输入:text = "we will we will rock you", first = "we", second = "will"
输出:["we","rock"]
复制代码
思考:
先将text按空字符分割,得到单词数组。
遍历单词数组,找到与first相同字符串再比较后一个单词与second是否相同,相同就将第三个单词加入结果集。
复制代码
实现:
class Solution {
public String[] findOcurrences(String text, String first, String second) {
List<String> res = new ArrayList<>();
String[] strings = text.split(" ");
for (int count = 0; count < strings.length - 2; count++) {
if (strings[count].equals(first) && strings[count + 1].equals(second)) {
res.add(strings[count + 2]);
}
}
return res.toArray(new String[res.size()]);
}
}复制代码
转载于:https://juejin.im/post/5cfe164ff265da1bc07e2e3d