【LeetCode】5083. Occurrences After Bigram 解题报告(Python & C++)

本文介绍了一道LeetCode上的编程题“Occurrences After Bigram”,目标是在长字符串中查找符合特定模式“firstsecondthird”的单词,其中first和second作为输入给出。文章详细解析了解题思路,包括字符串分割遍历的方法,并提供了Python和C++的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/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.

题目大意

找出在一个长字符串text中,符合"first second third"模式的third。其中first和second是输入的。

解题方法

字符串分割遍历

对字符串进行分割,然后循环遍历,每次判断三个单词,看前两个是不是first和second,如果满足的话那么把第三个放到结果中即可。

时间复杂度是O(N)。

Python代码如下:

class Solution(object):
    def findOcurrences(self, text, first, second):
        """
        :type text: str
        :type first: str
        :type second: str
        :rtype: List[str]
        """
        words = text.split()
        res = []
        L = len(words)
        for i in range(L - 2):
            f, s, t = words[i], words[i + 1], words[i + 2]
            if f == first and s == second:
                res.append(t)
        return res

C++代码的难点是字符串操作。C++竟然没有split()函数,这也是大家吐槽太多的点。一个可以替换的方案是使用stringstream类,该类会模拟字符串读入操作,即实现字符串按空格分割。初始化三个字符串,分别是f,s,t,读入到第三个里,前两个保留的是前两次读入的结果。这样进行判断是比较优雅的操作。

C++代码如下:

class Solution {
public:
    vector<string> findOcurrences(string text, string first, string second) {
        stringstream ss(text);
        vector<string> res;
        string f, s, t;
        while (ss >> t) {
            if (f == first && s == second) 
                res.push_back(t);
            f = s;
            s = t;
        }
        return res;
    }
};

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

日期

2019 年 6 月 9 日 —— 简单的题没有难度,需要挑战有难度的才行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值