843. Guess the Word
題目網址:https://leetcode.cn/problems/guess-the-word/
題意:給一由不同 string 所組成的單字列表
words
, 其中words[i]
長度均為6
。words
中的一個單字將被選作秘密單字secret
。另外, 給一輔助對象
Master
, 你可以調用Master.guess(word)
來猜單字, 其中參數word
長度為6
, 且必須是words
中的 string。
Master.guess(word)
將會返回以下結果:
- 若
word
不是words
中的 string, 則返回1
- 返回一個整數, 表示你所猜測的單詞
word
與secret
的準確匹配(值和位置同時匹配)的數目此外, 還會給一參數
allowedGuesses
, 代表調用Master.guess(word)
的最大次數。在不超過允許猜測次數的前提下, 你應該調用
Master.guess
來猜出secret
, 並得到以下結果:
- 若調用
Master.guess
的次數大於allowedGuesses
or 你沒有用Master.guess
猜到secret
, 則得到"Either you took too many guesses, or you did not find the secret word."
- 若調用
Master.guess
猜到secret
, 且調用Master.guess
的次數不超過allowedGuesses
, 則得到"You guessed the secret word correctly."
題目保證你可以透過某種合理的策略(而非暴力法)猜到
secret
。
Solution:
想法:利用刪去法
- 先隨機選擇一單字
s
, 然後計算s
與secret
的相似度cnt
- 若
cnt == 6
, 代表s
為secret
- 否則, 遍歷
words
中其他的單字word
, 並計算s
和word
的相似度
然後將count(s, word) == cnt
的單字加到filter
中
➔ 能這樣做是因為s
和secret
的相似度等於cnt
, 若剩下的單字word
要等於secret
, 則word
和s
的相似度必須要等於cnt
- 將
words
更新成filter
- 重複以上步驟直到
words
為空e.g.
secret = "acckzz"
,words = ["acckzz","ccbazz","eiowzz","abcczz"]
- 假設隨機選到
s = eiowzz
, 此時s
與secret
的相似度cnt = 2
- 遍歷
words
其他單字word
, 並把符合count(s, word) == 2
的單字加到filter
中word = acckzz
,count(s, word) = 2 = cnt
➔filter = {acckzz}
word = ccbazz
,count(s, word) = 2 = cnt
➔filter = {acckzz, ccbazz}
word = abcczz
,count(s, word) = 2 = cnt
➔filter = {acckzz, ccbazz, abcczz}
- 更新
words
➔words = {acckzz, ccbazz, abcczz}
- 假設隨機選到
s = abcczz
, 此時s
與secret
的相似度cnt = 4
- 遍歷
words
其他單字word
, 並把符合count(s, word) == 4
的單字加到filter
中word = acckzz
,count(s, word) = 4 = cnt
➔filter = {acckzz}
word = ccbazz
,count(s, word) = 2 != cnt
➔filter = {acckzz}
- 更新
words
➔words = {acckzz}
- 選
s = acckzz
, 此時s
與secret
的相似度cnt = 6
, 代表找到secret
class Solution { |
- time:$O(n^2)$ ➔ worse case:每次
s
都只從words
中剔除掉一個word
故時間複雜度為 $n + (n-1) + (n-2) + … + 1 = O(n^2)$ - space:$O(n)$ ➔
filter
的元素個數不超過n
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論