有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在字谜中找到重复的字母

我正在写一个程序,非常类似于节目倒计时。有一堆字母,你可以用它们来造单词

我已经完成了基础工作,用户提交的单词与基本单词对照检查,如果字符匹配,则与在线API字典对照检查。然后将分数添加到前10名排行榜中。我已经实现了所有这些,但我现在面临着我的最后一个问题,我似乎无法解决

// convert the users guess to a char array
char [] chars = word.toCharArray();

for(char c : chars){
    int charIndex = baseWord.indexOf(c);

    if(charIndex != -1){
        continue;
    } else {
        System.out.println("The letter " + c + " is not in " + baseWord);
        return false;
    }
}

我将用户猜测转换为字符数组,然后将字符数组的每个元素与基字的元素进行比较。在我有重复记录之前,这一切正常。例如,如果我将基字设置为areallylongword,而用户猜测设置为adder,则返回true,而应返回false

我理解在查找chardint charIndex = baseWord.indexOf(c)将返回相同值的概念

我如何避免这个问题


共 (3) 个答案

  1. # 1 楼答案

    一旦匹配,您可以从基字中删除这些字母

  2. # 2 楼答案

    将出现的字符计数到数组或哈希中,然后减少猜测单词的计数

    例如,如果假设基字应包含字母ASCI-128,则可以创建一个位置为128的数组,并使用字符码作为字母的索引

    char [] chars = word.toCharArray();
    int[] charCount = int[128]; // By default every position is 0
    for (c : chars) {
       charCount[c] += 1; // Increments the count of char 
    }
    

    然后检查用户的猜测词,并从这个charCount中减少,以验证用户是否猜对了,charCount上永远不应该有负数

    char[] c = guess.toCharArray();
    for (c : chars) {
       charCount[c] -= 1;
       if (charCount[c] < 0) {
         return 0;
       }
    }
    
  3. # 3 楼答案

    找到匹配项时,只需将baseWord中的字母留空即可:

    // convert the users guess to a char array
    char [] chars = word.toCharArray();
    
    for(char c : chars){
        int charIndex = baseWord.indexOf(c);
    
        if(charIndex != -1){
            char[] baseWordChars = baseWord.toCharArray();
            baseWordChars[charIndex] = '#';  // char wiped
            baseWord = new String(baseWordChars);
            continue;
        } else {
            System.out.println("The letter " + c + " is not in " + baseWord);
            return 0;
        }
    }