題目出處
難度
easy
個人範例程式碼
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
if not s:
return True
wordlist = s.split(" ")
worddict = {}
patterndict = {}
if not len(wordlist) == len(pattern):
return False
for idx, each_pattern in enumerate(pattern):
if each_pattern in patterndict:
if not patterndict[each_pattern] == wordlist[idx]:
return False
if wordlist[idx] in worddict:
if not worddict[wordlist[idx]] == each_pattern:
return False
patterndict[each_pattern] = wordlist[idx]
worddict[wordlist[idx]] = each_pattern
return True
算法說明
這題是考簡單的字串處理,但細節要注意很多,很難一次全對
確認同一 pattern 無重複配對 (word = a, b)
這個是要注意 word = a 且 word = b 要 return 為 False 的情況
確認同一 word 無重複配對 (word, code = a)
這個是要注意 word = a 且 code = a 要 return 為 False 的情況
確認本身長度不同的問題
這個是要注意 “aaa” 不等於 “aa aa”,等類似的狀況,需要多判斷長度是否相同。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
input handling
如果沒有 s,return True
Boundary conditions
for loop 控制範圍
[…] 【Leetcode】python – [290] Word Pattern 個人解法筆記 […]