↓快轉到主要內容
  1. LeetCode/

LeetCode 1078: Occurrences After Bigram

·1 分鐘· ·
LeetCode Easy String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-10-04

  • 提交紀錄:Runtime Error → Accepted ×3

解題思路
#

切成單字後看每個位置 i(String 模板六):words[i] == first、words[i + 1] == second 就收 words[i + 2]。迴圈只跑到 len(words) - 2,第三個字一定存在。

我的嘗試
#

第一版的邊界只檢查了 i + 1 < len(text),卻存取 text[i + 2]:"b b"、first = second = "b" 時 IndexError。改成檢查 i + 2 就 AC 了。

正確解法
#

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        w = text.split()
        return [w[i + 2] for i in range(len(w) - 2)
                if w[i] == first and w[i + 1] == second]

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 要用到 i + 2,邊界就要檢查到 i + 2。

面試口說整理
#

我把文字切成單字,檢查每個連續的三個單字,前兩個等於 first 和 second 就把第三個加進答案,迴圈只跑到倒數第三個。時間 O(n)。

相關文章

LeetCode 1047: Remove All Adjacent Duplicates In String
·1 分鐘
LeetCode Easy String Stack
LeetCode 1047 解題筆記:stack 頂端跟目前字元相同就一起消掉,否則放進 stack;消掉之後新的頂端可能又能跟下一個消
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開
LeetCode 1021: Remove Outermost Parentheses
·1 分鐘
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 解題筆記:用深度計數取代 stack,深度從 0 變 1 的左括號和從 1 變 0 的右括號是外層,其他都保留
LeetCode 929: Unique Email Addresses
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 929 解題筆記:用 @ 切開,只處理 local 的部分(+ 之後丟掉、去掉 .),接回 domain 後放進集合
LeetCode 944: Delete Columns to Make Sorted
·1 分鐘
LeetCode Easy Array String Longest-Increasing-Subsequence
LeetCode 944 解題筆記:用 zip(*strs) 取出每一欄,數有幾欄不是非遞減的
LeetCode 953: Verifying an Alien Dictionary
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 953 解題筆記:把字母對應到外星順序的 index,相鄰兩個單字找第一個不同的字元比較,沒有不同時短的要在前面