[LeetCode] Guess the Word

843. Guess the Word

This is an interactive problem.

You are given an array of unique strings wordlist where wordlist[i] is 6 letters long, and one word in this list is chosen as secret.

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.

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.

For each test case, you have exactly 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or fewer calls to Master.guess and at least one of these guesses was secret, then you pass the test case.

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
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* class Master {
* public:
* int guess(string word);
* };
*/
class Solution {
int match(string& origin, string& target) {
int count = 0;
for(int i = 0; i < origin.length(); i++) {
if(origin[i] == target[i]) count++;
}
return count;
}

void removeUnMatchStrings(vector<string>& words, string& picked, int matchCountFromMaster) {
for(int i = 0; i < words.size(); i++) {
int matchCount = match(picked, words[i]);
if(matchCount != matchCountFromMaster){
words.erase(words.begin() + i);
i--;
}
}
}

string pickOne(vector<string>& words) {
int arr[6][26]{0};
for(auto& w: words) {
for(int i = 0; i < 6; i++) {
arr[i][w[i]-'a']++;
}
}
int idx = 0, ch = 0, ma = 0;
for(int i = 0; i < 6; i++) {
int maxIdx, maxValue = 0;
for(int j = 0; j < 26; j++) {
if(arr[i][j] > maxValue) {
maxIdx = j;
maxValue = arr[i][j];
}
}
if(ma < maxIdx) {
ma = maxIdx;
ch = maxIdx;
idx = i;
}
}
for(auto& w : words) {
if(w[idx]-'a' == ch) return w;
}
return "";
}

public:
void findSecretWord(vector<string>& wordlist, Master& master) {
vector<pair<string, int>> history;
for(int i = 0; i < 10 and !wordlist.empty(); i++) {
string pick = pickOne(wordlist);
int masterMatchCount = master.guess(pick);
removeUnMatchStrings(wordlist, pick, masterMatchCount);
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/guess-the-word/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.