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

LeetCode 459: Repeated Substring Pattern

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

基本資料
#

難易度: easy 第一次嘗試:2022-08-24

  • 提交紀錄:Accepted(一次通過)

解題思路
#

直接做法:枚舉能整除 n 的長度 L,檢查 s[:L] * (n // L) == s。更短的寫法:把 s + s 去掉第一個和最後一個字元,如果 s 還在裡面,代表 s 旋轉一個不是 0、也不是 n 的距離之後跟自己相同,也就是有重複的週期(String 模板二)。

我的嘗試
#

一次 AC,當時寫的是 s in s[1:] + s[:-1],跟 (s + s)[1:-1] 是同一個字串。

正確解法
#

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        return s in (s + s)[1:-1]

複雜度
#

時間 O(n²)(內建搜尋最壞情況),空間 O(n)。

要特別避免的錯誤
#

  • 頭尾都要去掉,不然 s 一定會在 s + s 的開頭或結尾找到。

面試口說整理
#

如果 s 是由子字串重複組成的,它旋轉某個週期之後會跟自己一樣,所以我檢查 s 是否出現在 s + s 去掉頭尾字元的字串裡。面試時也可以講枚舉能整除長度的週期,再逐一驗證。

相關文章

LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 1446: Consecutive Characters
·1 分鐘
LeetCode Easy String
LeetCode 1446 解題筆記:掃一次記錄目前連續相同字元的長度,遇到不同就重設成 1
LeetCode 1869: Longer Contiguous Segments of Ones than Zeros
·1 分鐘
LeetCode Easy String
LeetCode 1869 解題筆記:分別找出最長的連續 1 和最長的連續 0,比較大小;用 split 一行就能做
LeetCode 415: Add Strings
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 415 解題筆記:兩個指標從尾巴往前逐位相加,記錄進位,迴圈結束後還有進位要補上
LeetCode 482: License Key Formatting
·1 分鐘
LeetCode Easy String
LeetCode 482 解題筆記:先去掉所有 - 並轉大寫,再從尾巴每 k 個切一段,最前面那段可以比較短
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小