对于这个挑战,我需要找到重复字母数最多的单词。例如,如果我输入Hello
,则输出应为2
,因为它包含l
或No words
的{{1}}个字符,且应为-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++;
}
}
}
}
}
答案 0 :(得分:2)
你几乎做到了,我想你正在研究这样的事情:
static int mostFreqCharCount(final String word) {
final int chars[] = new int[256];
int max = 0;
for (final char c : word.toCharArray()) {
chars[c]++;
if (chars[c] > chars[max]) // find most repetitive symbol in word
max = c;
}
return chars[max];
}
public static void main(final String[] args) {
System.out.println("Enter any sentence or word combination: ");
final Scanner kbd = new Scanner(System.in);
final String myString = kbd.nextLine();
kbd.close();
int maxC = 0;
String result = "";
final String[] words = myString.split("\\s+");
for (final String word : words) {
final int c = mostFreqCharCount(word);
if (c > maxC) {
maxC = c;
result = word;
}
}
if (maxC > 1) // any word has at least 1 symbol, so we should return only 2+
System.out.println(result);
}
主要想法 - 计算每个单词最常用符号的数量,并仅在变量maxC
和result
答案 1 :(得分:0)
您想要创建一个length = words.length的数组,并将每个单词的最高值存储在其相对索引中:
int counts[] = new int[words.length];
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length(); j++){
count = 0
for(int k = k+1; k < words[i].length(); k++){
if(words[i].charAt(j) == words[i].charAt(k)){
count++;
}
if(counts[i] < count)
counts[i] = count;
}
}
然后只扫描数组中的最高值n,并返回单词[n]
答案 2 :(得分:0)
如果你只需要一个计数最多的单词,你只需要三个变量,一个用于currentBestWord,一个用于currentLargestCount,另一个用于保持单词中的字符数。
int currentLargestCount=0;
String currentBestWord="";
HashMap<String,Integer> characterCount=new HashMap<String,Integer>();
String[] words=myString.split("\\s+");
for(int i=0;i<words.length;i++){
String w=words[i];
characterCount=new HashMap<String,Integer>();
for(int j=0;j<w.length();j++){
String character=w.charAt(j).toString();
if(characterCount.containsKey(character)){
characterCount.put(character,characterCount.get(character)+1);
}else{
characterCount.put(character,1);
}
}
// Now get the largest count of this word
Iterator ir=characterCount.ValueSet().iterator();
int thiscount=0;
while(ir.hasNext()){
int thischaractercount=ir.next();
if(thiscount<thischaractercount) thiscount=thischaractercount;
}
if(thiscount>currentLargestCount){
currentLargestCount=thiscount;
currentBestWord=w;
}
}