关于leetcode:leetcode之Bigram分词

3次阅读

共计 954 个字符,预计需要花费 3 分钟才能阅读完成。

本文次要记录一下 leetcode 之 Bigram 分词

题目

 给出第一个词 first 和第二个词 second,思考在某些文本 text 中可能以 "first second third" 模式呈现的状况,其中 second 紧随 first 呈现,third 紧随 second 呈现。对于每种这样的状况,将第三个词 "third" 增加到答案中,并返回答案。示例 1:输出:text = "alice is a good girl she is a good student", first = "a", second = "good"
输入:["girl","student"]
示例 2:输出:text = "we will we will rock you", first = "we", second = "will"
输入:["we","rock"]
 

提醒:1 <= text.length <= 1000
text 由一些用空格分隔的单词组成,每个单词都由小写英文字母组成
1 <= first.length, second.length <= 10
first 和 second 由小写英文字母组成


起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/occurrences-after-bigram
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

class Solution {public String[] findOcurrences(String text, String first, String second) {String[] textArr = text.split(" ");
        List<String> result = new ArrayList<>();
        for (int i=0; i< textArr.length-2 ; i++) {if (textArr[i].equals(first) && textArr[i + 1].equals(second)) {result.add(textArr[i + 2]);
            }
        }
        return result.toArray(new String[result.size()]);
    }
}

小结

这里先对 text 按空格分隔为字符串数组,之后遍历数组判断是否满足 first 及 second,都满足则将 third 增加到后果中。

doc

  • Bigram 分词
正文完
 0