原题说明
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 <= text.length <= 1000
text
consists of space separated words, where each word consists of lowercase English letters.1 <= first.length, second.length <= 10
first
andsecond
consist of lowercase English letters.
解题思路
题目的要求很简单,找出在first
、second
出现后紧跟着的第三个单词,而整句话是由空格和单词组成的。我们直接利用istringstream
这个类处理串流,切分整句话,如果数组的当前元素的上一个元素等于second
,且当前元素的上上一个元素等于first
,就将当前元素添加进答案vector
,最后返回记录答案的vector
即可。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)
视频讲解
我们在Youtube上更新了视频讲解,欢迎关注!