Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

A previous method called letterCounts required "counts the number of times that each letter occurs in the specified string and returns the result as an int array, where the number of ‘A’s is stored at position [0], the number of ‘B’s is stored at position [1], and so on:".

Now I have tried to create the method wordInLetters but I am stuck as to how to proceed to create a method that does what the title of this post says.

static boolean wordInLetters(final String word, final int[] letterCounts) {
boolean hasEnough = true;
for (int i = 0; i <word.length(); i ++){
    if (word.charAt(i) < letterCounts[i]){
       hasEnough = false;
     
    }
    else {return true;}
}
return hasEnough;
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

Call the previously made function, passing the word as parameter. Then compare the values returned by it with the values in letterCount array. If they are all <= return true.

Note: this assumes both arrays have the same length (i.e. 26 for ASCII alphabet).

static boolean wordInLetters(final String word, final int[] availableLetters)
{
    // Get the count of letters in the word
    int [] lettersInWord = letterCounts(word);
    // Compare the counts
    for (int i = 0; i < lettersInWord.length; i++) {
        // If not enough letters, fail
        if (availableLetters[i] < lettersInWord[i]) {
            return false;
        }
    }
    // If we made it to here, all is good.
    return true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...