zoukankan      html  css  js  c++  java
  • [LeetCode] 1078. Occurrences After Bigram 双元语法分词


    Given words first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second.

    For each such occurrence, add "third" to the answer, and return the answer.

    Example 1:

    Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
    Output: ["girl","student"]
    

    Example 2:

    Input: text = "we will we will rock you", first = "we", second = "will"
    Output: ["we","rock"]
    

    Note:

    1. 1 <= text.length <= 1000
    2. text consists of space separated words, where each word consists of lowercase English letters.
    3. 1 <= first.length, second.length <= 10
    4. first and second consist of lowercase English letters.

    这道题说是给了两个单词 first 和 second,又给了一段文字 text,现在让找出所有紧跟着 first 和 second 后面的第三个单词。这道题标记为 Easy,其实也没什么难度,首先就是要把 text 中的单词都拆分出来,此时又到了羡慕 Java 有 split 函数,吐槽 C++ 的功能不够强大的时间了。没办法,谁让博主老早就上了 C++ 这条贼船了呢,老老实实的用字符串流类吧,新建一个数组 words,用来保存分离出来的单词。对于每个单词,看下其前面的两个单词是否分别等于 first 和 second,等于的话就将当前单词加入到结果 res 中即可,最后别忘了还要将当前单词加入 words 数组,参见代码如下:


    解法一:

    class Solution {
    public:
        vector<string> findOcurrences(string text, string first, string second) {
            vector<string> res, words;
            istringstream iss(text);
            string t;
            while (iss >> t) {
                int n = words.size();
                if (n >= 2 && words.back() == second && words[n - 2] == first) res.push_back(t);
                words.push_back(t);
            }
            return res;
        }
    };
    

    其实我们并不用保存所有的单词,因为这里只关心前两个单词是啥,所以可以使用两个变量 pre2 和 pre 来记录前面的两个单词,当其分别等于 first 和 second 的时候,将当前单词加入结果 res 中,并且 pre2 赋值为 pre,pre赋值为当前单词即可,参见代码如下:


    解法二:

    class Solution {
    public:
        vector<string> findOcurrences(string text, string first, string second) {
            vector<string> res, words;
            istringstream iss(text);
            string t, pre, pre2;
            while (iss >> t) {
                if (pre2 == first && pre == second) res.push_back(t);
                pre2 = pre;
                pre = t;
            }
            return res;
        }
    };
    

    Github 同步地址:

    https://github.com/grandyang/leetcode/issues/1078


    参考资料:

    https://leetcode.com/problems/occurrences-after-bigram/

    https://leetcode.com/problems/occurrences-after-bigram/discuss/308385/C%2B%2B-stringstream

    https://leetcode.com/problems/occurrences-after-bigram/discuss/308224/JavaPython-3-Split-String.


    LeetCode All in One 题目讲解汇总(持续更新中...)

  • 相关阅读:
    Android Studio 插件
    天气预报接口api(中国天气网)
    使用easyui的Tree 实现无限子节点绑定
    js调用后台方法
    div窗口效果来自标准之路
    C#生成dll程序集文件
    一个技术人的博客
    HTML-embed标签详解
    网站生成桌面快捷图标
    文本框宽度自动适应文本宽度
  • 原文地址:https://www.cnblogs.com/grandyang/p/14588197.html
Copyright © 2011-2022 走看看