-
Notifications
You must be signed in to change notification settings - Fork 112
/
0843-GuesstheWord.cs
78 lines (65 loc) · 2.15 KB
/
0843-GuesstheWord.cs
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//-----------------------------------------------------------------------------
// Runtime: 92ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _0843_GuesstheWord
{
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* class Master {
* public int Guess(string word);
* }
*/
public void FindSecretWord(string[] wordlist, Master master)
{
var random = new Random();
var wordlistHashSet = new HashSet<string>(wordlist);
for (int i = 0; i < 10; i++)
{
var word = wordlistHashSet.ElementAt(random.Next(wordlistHashSet.Count));
var result = master.Guess(word);
if (result == word.Length) return;
wordlistHashSet.RemoveWhere(anotherWord => MatchCount(word, anotherWord) != result);
wordlistHashSet.Remove(word);
}
}
public int MatchCount(string word1, string word2)
{
var count = 0;
for (int i = 0; i < word1.Length; i++)
if (word1[i] == word2[i])
count++;
return count;
}
}
public class Master
{
private readonly string secret;
private readonly HashSet<string> wordlist;
public Master(string secret, string[] wordlist)
{
this.secret = secret;
this.wordlist = new HashSet<string>(wordlist);
GuessCount = 0;
}
public int GuessCount { get; set; }
public int Guess(string word)
{
GuessCount++;
if (this.secret.Length != word.Length) { return -1; }
if (!wordlist.Contains(word)) { return -1; }
var count = 0;
for (int i = 0; i < word.Length; i++)
if (word[i] == secret[i])
count++;
return count;
}
}
}