Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

java - Method that returns whether a specified word can be made with specified letter counts

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;
}

}


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

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...