LeetCode 843 题解

https://leetcode.com/problems/guess-the-word/description/

题目大意:一道交互式的题目(类似2018年google的code jam),给你一个字典,其中一个String是从字典中取出来的,问给你10次机会,找到这个String,每次询问会返回给你你选择的String和待找到的String相同位置的个数。

解题思路:随机选一个String,得到和待找String比较相同位置的个数x,此时查找整个字典,找到和随机选择的String比较位置相同个数为x的全部String, 将他们存到一个List里,此时 待比较的String肯定也在这个List里,同时也能去除很多不是最终结果的答案。

class Solution {
    private int judge(String a,String b)
    {
        int len =a.length();
        int cnt =0;
        for(int i=0;i<len;i++)
        {
            if(a.charAt(i)==b.charAt(i))
                cnt++;
        }
        return cnt;
    }
    private void find(List<String> w,Master master)
    {
        int len = w.size();
        if(len==0) return ;
        Random random = new Random();
        int x = random.nextInt(len);
        int c = master.guess(w.get(x));

        //System.out.println(x+" "+len);

        List<String> tmp = new ArrayList<>();
        for(int i=0;i<len;i++)
        {
            //System.out.println(w.get(i));
            if(i!=x && judge(w.get(x),w.get(i))==c)
                tmp.add(w.get(i));
        }
        find(tmp,master);
    }
    public void findSecretWord(String[] wordlist, Master master) {
        List<String> res = Arrays.asList(wordlist);
        find(res,master);
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80482508