【发布时间】:2020-05-22 18:18:53
【问题描述】:
文本将仅包含空格和单词。
示例输入:
thanks for the help \n
the car works now \n
thanks \n
输出: - 因为它的字典顺序小于“Thanks”。
public class Main {
public static void main(String[] args) throws IOException {
String line;
String[] words = new String[100];
Map < String, Integer > frequency = new HashMap < > ();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) {
words = line.split("\\W+");
for (String word: words) {
String processed = word.toLowerCase();
processed = processed.replace(",", "");
if (frequency.containsKey(processed)) {
frequency.put(processed,
frequency.get(processed) + 1);
} else {
frequency.put(processed, 1);
}
}
}
}
int mostFrequentlyUsed = 0;
String theWord = null;
for (String word: frequency.keySet()) {
Integer theVal = frequency.get(word);
if (theVal > mostFrequentlyUsed) {
mostFrequentlyUsed = theVal;
theWord = word;
} else if (theVal == mostFrequentlyUsed && word.length() <
theWord.length()) {
theWord = word;
mostFrequentlyUsed = theVal;
}
}
System.out.printf(theWord);
}
}
我没有通过一项测试,我真的不知道为什么我需要另一种方法。
【问题讨论】:
-
你能提供一个你尝试过的代码示例吗?
-
我已经添加了我的解决方案,也许我可以找到其他方法...
-
@GeorgeChetan,请格式化您的代码并使其更具可读性
-
@HarshalParekh 对不起...
标签: java arrays string bufferedreader treemap