【发布时间】:2015-05-15 04:56:46
【问题描述】:
对于这个挑战,我需要找到重复字母数量最多的单词。例如,如果我输入Hello world!,则输出应该是Hello,因为它包含l 的2 字符,或者No words,它应该是-1。
我将问题分解为:
1) 将一句话破入words的数组中
2) 循环遍历每个word
3) 循环遍历每个charcater
如果一个单词包含的字母比其他单词多,我应该如何返回。
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter any sentence or word combination: ");
String myString = kbd.nextLine();
String result = "";
int count = 0;
String[] words = myString.split("\\s+");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length(); j++) {
for(int k = 1; k < words[i].length(); k++) {
char temp = words[i].charAt(k);
if(temp == words[i].charAt(k-1)) {
count++;
}
}
}
}
}
【问题讨论】:
-
你能定义重复的字母吗? “hello”、“heelloo”的重复次数是多少?
-
或者
banana?这个值是 3 吗? -
我不明白你的k循环在做什么,你不应该从k=j+1开始比较
.charAt(j) to .charAt(k)吗?您还需要将每个单词的计数变量归零,可能是每个字母(取决于您如何定义计数)。 -
@BenjyKessler,它应该返回具有相同第一个重复字母的单词。在
"heelloo"中,它应该是e,因为它首先出现。 -
@Tony,是的,正确的。
标签: java