---
# System prepended metadata

title: 0843. Guess the Word
tags: [Leetcode, Hard]

---

# 0843. Guess the Word
###### tags: `Leetcode` `Hard`
Link: https://leetcode.com/problems/guess-the-word/description/
## 思路
每次我们都在words里面随便抽取一个单词
然后看它与secret word的match
如果match=6 找到答案
如果不行我们需要使words list缩小
这样我们才能更有效率的查找
因此我们把所有和```guess```有exactly```matches```个字母重合的word全都加进list里面
这样就避免了我们重复把```guess```加进去 并且能保证secret word还在里面 如果用>=反而效率不高
## Code
```java=
class Solution {
    public void findSecretWord(String[] words, Master master) {
        Random rand = new Random();
        for(int i=0; i<30; i++){
            String guess = words[rand.nextInt(words.length)];
            int matches = master.guess(guess);
            if(matches==6) break;
            List<String> next = new ArrayList<>();
            for(String w:words){
                if(match(w, guess)==matches){
                    next.add(w);
                }
            }
            words = next.toArray(new String[0]);
        }
    }
    private int match(String s, String t){
        int cnt = 0;
        for(int i=0; i<6; i++){
            if(s.charAt(i)==t.charAt(i)) cnt++;
        }
        return cnt;
    }
}
```