iT邦幫忙

2021 iThome 鐵人賽

DAY 30
0
自我挑戰組

30天 Leetcode解題之路系列 第 30

Day 30 - Occurrences After Bigram

  • 分享至 

  • xImage
  •  

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
來到30天的最後一天解題Day啦~


1078. Occurrences After Bigram

Question

Given two strings 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.

Return an array of all the words third for each occurrence of "first second third".


Example

Example1

Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl","student"]

Example2

Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]

Constraints

  • 1 <= text.length <= 1000
  • text consists of lowercase English letters and spaces.
  • All the words in text a separated by a single space.
  • 1 <= first.length, second.length <= 10
  • first and second consist of lowercase English letters.

解題

題目

首先先簡單的翻譯一下題目
給一個字串句子,然後給firstsecond兩個字串,要找到所有符合條件的third字串,條件就是first下一個要接著second,second下一個要接third。

Think

作法大致上是這樣

  • 就照著上面的想法,每個index都往下兩個index判斷是否符合。
  • 感覺改成while,讓符合條件存入list的時候讓index直接跳到下下一個位置的index可能可以再縮短一點執行時間。

Code

Python

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        list_text = text.split(" ")
        ans = []
        
        for index in range(len(list_text)):
            
            if list_text[index] == first:
                if index+1 <= len(list_text)-1 and list_text[index+1] == second:
                    if index+2 <= len(list_text)-1:
                        ans.append(list_text[index+2])
        
        return ans

Result

  • Python

大家下次見/images/emoticon/emoticon29.gif


上一篇
Day 29 - Baseball Game
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 3 級 ‧ 2021-10-15 02:50:40

恭喜完賽!

我要留言

立即登入留言