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"]
-
提示:
1 <= text.length <= 1000
text
由一些用空格分隔的单词组成,每个单词都由小写英文字母组成1 <= first.length, second.length <= 10
first
和second
由小写英文字母组成
-
代码1:
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
temp = []
a = text.split(' ')
for i in range(len(a)-2):
if a[i] == first and a[i+1] == second:
temp.append(a[i+2])
return temp
# 执行用时 :68 ms, 在所有 Python3 提交中击败了16.27%的用户
# 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了100.00%的用户
- 算法说明:
先将文本用split
函数分割,然后逐个判断当前元素和first
,当前的下一个元素和second
是否相等,如果都相等,则将第三个元素附加给temp
列表,最后输出temp
列表。