我正在尝试解决下面概述的编程挑战,其中基本上你需要在给定的句子中找到重复字符最多的单词。我对此有点挣扎,并且很幸运地找到了一些代码来计算字符串中字母的出现次数(也在下面)。这段特定的代码将所有字母存储在一个 HashMap 中,我需要对其进行定制,以便它单独存储每个单词的字符出现(而不是像现在那样聚合)。这就是我卡住的地方。我可以用什么来存储 HashMap 循环的每次迭代的状态?
/* Using the Java language, have the function LetterCountI(str) take
* the str parameter being passed and return the first word with the
* greatest number of repeated letters. For example: "Today, is the
* greatest day ever!" should return greatest because it has 2 e's
* (and 2 t's) and it comes before ever which also has 2 e's. If there
* are no words with repeating letters return -1. Words will be
* separated by spaces. */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class OtherCountLetters {
void countLetters2(String str) {
String[] words = str.toLowerCase().split(" ");
Map<Character, Integer> numChars = new HashMap<Character, Integer>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words[i].length(); j++) {
char charAt = words[i].charAt(j);
if (!numChars.containsKey(charAt)) {
numChars.put(charAt, 1);
} else {
numChars.put(charAt, numChars.get(charAt) + 1);
}
}
}
System.out.println(numChars);
}
public static void main(String[] args) {
OtherCountLetters ocl = new OtherCountLetters();
ocl.countLetters2("Today is the greatest day ever");
}
}
此刻,对于“今天是有史以来最伟大的一天”这句话,程序返回
{v=1, g=1, d=2, e=5, t=4, s=2, r=2, a=3, o=1, h=1, y=2, i=1}
但我需要它来返回类似的东西
{a=1, d=1, o=1, t=1, y=1} //'today'
{i=1, s=1} //'is'
{e=1, h=1, t=1} //'the'
{g=1, t=2, e=2, s=1, r=1, a=1} //'greatest'
{d=1, a=1, y=1} //'day'
{v=1, e=2, r=1} //'ever'
这样,我可以遍历每个条目以查看哪个条目具有最大值,然后将相应的单词返回给用户。
谢谢,
- - -编辑 - -
发布此消息后,我有一个尤里卡时刻:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class OtherCountLetters {
void countLetters2(String str) {
String[] words = str.toLowerCase().split(" ");
String target = null;
int largest = 0;
Map<Character, Integer> numChars = new HashMap<Character, Integer>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words[i].length(); j++) {
char charAt = words[i].charAt(j);
if (!numChars.containsKey(charAt)) {
numChars.put(charAt, 1);
} else {
numChars.put(charAt, numChars.get(charAt) + 1);
}
if (numChars.get(charAt) > largest) {
largest = numChars.get(charAt);
target = words[i];
}
}
numChars.clear();
}
if (largest != 1) {
System.out.println(target);
} else {
System.out.println("there are no words with 2 or more letters");
}
}
public static void main(String[] args) {
OtherCountLetters ocl = new OtherCountLetters();
ocl.countLetters2("today is the greatest day ever and car");
}
}