leetcode1078 Occurrences After Bigram

时间:2022-07-23
本文章向大家介绍leetcode1078 Occurrences After Bigram,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意分析

这个题意比较简单

首先来看输入:输入三个字符串,第一个字符串为 text,第二个字符串为 first,第三个字符串为 second。

查找过程:找到 text 中以 first 开始,second 连续的位置,然后输出 second 后的那个单词,记为 third,如果有多个位置符合,则需要找出每个 third 对应的单词。

最后输出:third 组成的列表

实现思路

很容易想到 string.split() 方法,将 first 与 second 通过空格拼接,然后根据拼接得到的单词去做 split 。这样基本上就可以拿到需要的结果了。

因为最后需要只需要后一个单词,所以对 split 拿到的结果做一点简单的处理,即再次根据空格做 split,然后取第一个值即可

上代码

class Solution(object):
    def findOcurrences(self, text, first, second):
        """
        :type text: str
        :type first: str
        :type second: str
        :rtype: List[str]
        """
        if not text:
            return []

        tmp = first + ' ' + second
        tlist = text.split(tmp)
        result = [s.strip().split(" ")[0] for s in tlist[1:] if s]

        for i in range(len(result)):
            # 这种情况原因,可参考题目中第二个示例
            if not result[i]:
                result[i] =  first
        return result

if __name__ == "__main__":
    s = Solution()
    print(s.findOcurrences("we will we will rock you", "we", "will"))