LeetCode:1078.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"]

源码:

class Solution {
    public String[] findOcurrences(String text, String first, String second) {
        StringBuilder sb = new StringBuilder();
        String[] str = text.split(" ");
        for (int i = 1; i < str.length - 1; i++) {
            if (str[i - 1].equals(first) && str[i].equals(second)) {
                sb.append(str[i + 1]);
                // 多往 sb 中添加一个空格,以便于后序的 split 操作
                sb.append(' ');
            }
        }
        // 如果 sb 长度为 0,说明没有符合题目要求的字符串
        if (sb.length() == 0) {
            return new String[0];
        }
        return sb.toString().split(" ");
    }
}
发布了351 篇原创文章 · 获赞 2 · 访问量 9174

猜你喜欢

转载自blog.csdn.net/qq_45239139/article/details/104124204
今日推荐