[英]Method that returns whether a specified word can be made with specified letter counts
之前的方法letterCounts需要“计算每个字母在指定字符串中出现的次数,并将结果作为int数组返回,其中'A'的数量存储在position [0]中,'B'的数量存储在在 position [1],依此类推:”。
现在,我尝试创建 wordInLetters 方法,但我不知道如何继续创建一个执行本文标题所述的方法。
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;
}
}
调用之前制作的 function,将单词作为参数传递。 然后将它返回的值与letterCount
数组中的值进行比较。 如果它们都是<=
返回 true。
注意:这假设 arrays 具有相同的长度(即 ASCII 字母为26
)。
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;
}
无需调用其他方法。 你可以简单地这样做:
static boolean wordInLetters(final String word, final int[] letterCounts) {
int start = 'a';
for (int i = 0; i < word.length(); i ++){
final int x = i;
Long count = Arrays.asList(word.split("")).stream()
.filter(w -> w.equals(word.substring(x, x + 1)))
.count();
if (letterCounts[word.charAt(i) - start] < count) {
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.