我目前正在开发一个最小堆,它将句子中的 F 数量从最少的 F 数量到最多的 F 数量进行排序,例如,如果用户输入
有趣
蓬松
法夫
五美元英尺长五美元
噗噗噗噗!
农民弗雷德·费德尔斯(Fred Fiddles)寻找食物
周五之后担心 final 。害怕吧 friend 。
它会将其排序为:
有趣
法夫
蓬松
五美元英尺长五美元
农民弗雷德·费德尔斯(Fred Fiddles)寻找食物
周五之后担心 final 。害怕吧 friend 。
噗噗噗噗!
我的问题是,如何将下面的代码结构转换为让用户自己输入句子并以 F 计数器作为权重,而不是自己将它们添加到堆中:
heap.insert("FUN",1);
heap.insert("Fluffy", 3);
heap.insert("Fife", 2);
heap.insert("Five Dollar Foot Long For Five Dollars", 4);
heap.insert("FfffFFffuuu!", 8);
heap.insert("Farmer Fred Fiddles for Food", 5);
heap.insert("After Friday fear the final. Be afraid friend.", 6);
最佳答案
您可以使用扫描仪从控制台读取输入,然后使用一种方法来计算单词中 f 的数量。
Scanner s = new Scanner(System.in);
while(true) {
String sentence = s.next();
switch(sentence) {
case "Sort":
//sort heap
break;
default:
countAndInsert(sentence);
break;
}
}
其中 countAndInsert
看起来像:
public void countAndInsert(String sentence) {
int fCount = 0;
for (char c : sentence.toCharArray()) {
if (c == 'F' || c == 'f') {
fCount++;
}
}
heap.insert(sentence, fCount);
}
关于java - 将句子添加到堆中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36608969/