Easy

题目描述

给定两个字符串 firstsecond,考虑在文本中出现的形式为 “first second third” 的词组,其中 second 紧跟在 first 后面,third 紧跟在 second 后面。

返回所有出现 “first second third” 中第三个单词 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 由小写英文字母和空格组成
  • text 中的所有单词由单个空格分隔
  • 1 <= first.length, second.length <= 10
  • firstsecond 由小写英文字母组成
  • text 开头和结尾都没有空格

解题思路

解题思路

这道题的核心是找到文本中符合 “first second third” 模式的词组,并收集所有的 third 单词。

基本思路:

  1. 将文本按空格分割成单词数组
  2. 遍历单词数组,检查连续的三个单词是否符合模式
  3. 如果前两个单词分别等于 first 和 second,则将第三个单词加入结果

具体实现:

  • 使用滑动窗口的思想,每次检查三个连续的单词
  • 从索引 0 开始,遍历到 length-2(确保有足够的单词组成三元组)
  • 当 words[i] == first 且 words[i+1] == second 时,将 words[i+2] 添加到结果中

这种方法时间复杂度为 O(n),其中 n 是单词数量,空间复杂度为 O(n) 用于存储分割后的单词数组。

注意事项:

  • 需要确保数组有至少 3 个元素才能形成有效的三元组
  • 字符串比较时要注意大小写(题目中都是小写字母)

代码实现

class Solution {
public:
    vector<string> findOcurrences(string text, string first, string second) {
        vector<string> result;
        istringstream iss(text);
        string word;
        vector<string> words;
        
        while (iss >> word) {
            words.push_back(word);
        }
        
        for (int i = 0; i <= (int)words.size() - 3; i++) {
            if (words[i] == first && words[i + 1] == second) {
                result.push_back(words[i + 2]);
            }
        }
        
        return result;
    }
};
class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        words = text.split()
        result = []
        
        for i in range(len(words) - 2):
            if words[i] == first and words[i + 1] == second:
                result.append(words[i + 2])
        
        return result
public class Solution {
    public string[] FindOcurrences(string text, string first, string second) {
        string[] words = text.Split(' ');
        List<string> result = new List<string>();
        
        for (int i = 0; i <= words.Length - 3; i++) {
            if (words[i] == first && words[i + 1] == second) {
                result.Add(words[i + 2]);
            }
        }
        
        return result.ToArray();
    }
}
var findOcurrences = function(text, first, second) {
    const words = text.split(' ');
    const result = [];
    
    for (let i = 0; i <= words.length - 3; i++) {
        if (words[i]

复杂度分析

复杂度类型复杂度说明
时间复杂度O(n)n 为单词数量,需要遍历一次单词数组
空间复杂度O(n)需要存储分割后的单词数组和结果数组