This problem is an interactive problem new to the LeetCode platform.html
We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.git
You may call master.guess(word)
to guess a word. The guessed word should have type string
and must be from the original list with 6 lowercase letters.github
This function returns an integer
type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1
instead.api
For each test case, you have 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or less calls to master.guess
and at least one of these guesses was the secret, you pass the testcase.數組
Besides the example test case below, there will be 5 additional test cases, each with 100 words in the word list. The letters of each word in those testcases were chosen independently at random from 'a'
to 'z'
, such that every word in the given word lists is unique.less
Example 1: Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"] Explanation: `master.guess("aaaaaa")` returns -1, because `"aaaaaa"` is not in wordlist. `master.guess("acckzz")` returns 6, because `"acckzz"` is secret and has all 6 matches. `master.guess("ccbazz")` returns 3, because` "ccbazz"` has 3 matches. `master.guess("eiowzz")` returns 2, because `"eiowzz"` has 2 matches. `master.guess("abcczz")` returns 4, because `"abcczz"` has 4 matches. We made 5 calls to master.guess and one of them was the secret, so we pass the test case.
Note: Any solutions that attempt to circumvent the judge will result in disqualification.dom
這道題號稱是 LeetCode 平臺上第一個交互式的題目,但定睛一看,踩比贊多,哎,創新不易啊~ 這道題說是有一個單詞數組 wordlist,其中有一個單詞是須要被猜到的單詞 secret,如今有一個 api 函數 guess,能夠返回猜的單詞和目標單詞之間的匹配個數。如今每一個 test case 有 10 次機會去猜目標單詞,假如調用 api 的次數不超過 10 次,並猜中了目標單詞的話,就能夠經過測試。首先,因爲須要儘量少的調用 api,因此線性的一個一個的對每一個單詞調用 api 是不可取的,由於假如目標單詞在最後一個,且單詞數組長度超過 10 個,就會失敗。這樣的話能夠隨機取一個單詞來檢測,調用 api 後會獲得一個次數 cnt,表示當前單詞和目標單詞之間的匹配個數。接下來怎麼辦呢?須要過濾一遍單詞數組,本身寫一個相似於 api 的函數,返回任意兩個單詞之間的匹配個數,這樣就能夠 filter 整個單詞數組了,由於藏在普通單詞中的目標單詞跟當前單詞調用 match 函數的返回值必定仍是 cnt,固然也會有其餘的單詞一樣返回 cnt,不過不要緊,仍是能濾去一大波不相干的單詞,重複這個步驟,直到 cnt 正好爲6中止,由於題目中說了單詞的長度就是6,參見代碼以下:ide
class Solution { public: void findSecretWord(vector<string>& wordlist, Master& master) { for (int i = 0, cnt = 0; i < 10 && cnt < 6; ++i) { string guess = wordlist[rand() % (wordlist.size())]; cnt = master.guess(guess); vector<string> t; for (string &word : wordlist) { if (match(guess, word) == cnt) { t.push_back(word); } } wordlist = t; } } int match(string& a, string& b) { int res = 0, n = a.size(); for (int i = 0; i < n; ++i) { if (a[i] == b[i]) ++res; } return res; } };
Github 同步地址:函數
https://github.com/grandyang/leetcode/issues/843測試
參考資料: