File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments