Skip to content

Commit 78e53ed

Browse files
committed
Add a solution to Guess Word
1 parent a0e6b51 commit 78e53ed

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Design/GuessWord.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/guess-the-word/
3+
* Primary idea: Random select a word and check the match count. Filter all words having the same match count.
4+
*
5+
* Time Complexity: O(n), Space Complexity: O(n)
6+
*
7+
* // This is the Master's API interface.
8+
* // You should not implement it, or speculate about its implementation
9+
* class Master {
10+
* public func guess(word: String) -> Int {}
11+
* }
12+
*/
13+
14+
class GuessWord {
15+
func findSecretWord(_ words: [String], _ master: Master) {
16+
var words = words
17+
18+
for i in 0..<30 {
19+
let trial = words[words.count / 2]
20+
let count = master.guess(trial)
21+
22+
if count == 6 {
23+
return
24+
}
25+
26+
var possibilities = [String]()
27+
for word in words {
28+
if matchCount(trial, word) == count {
29+
possibilities.append(word)
30+
}
31+
}
32+
words = possibilities
33+
}
34+
35+
}
36+
37+
private func matchCount(_ wordA: String, _ wordB: String) -> Int {
38+
var res = 0
39+
40+
for (charA, charB) in zip(wordA, wordB) {
41+
if charA == charB {
42+
res += 1
43+
}
44+
}
45+
46+
return res
47+
}
48+
}

0 commit comments

Comments
 (0)