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