gpt4 book ai didi

java - 给定一个字符串作为输入,返回在字符串中出现次数最多的字符

转载 作者:行者123 更新时间:2023-12-01 11:11:23 25 4
gpt4 key购买 nike

您可以假设只有 1 个字符会出现最多次数。

         Input             |     Output  
---------------------------+--------------
mostFreq("hello") | l
mostFreq("1223334445555") | 5
mostFreq("z") | z
<小时/>
public char mostFreq(String str){

int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{

char c=str.charAt(i); // take one character (c) in string

for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{

count=count+1;

}
}

if(temp.indexOf(c)==-1) // if it is not already counted
{

temp=temp+c; // append the character to the temp indicating
// that you have already counted it
}
return c;
}
return 0;

}

我尝试运行上面的代码,但失败了,请问有什么建议吗?

最佳答案

试试这个。

public char mostFreq(String str){

int highestFreq = 0;

char mostFreqChar = ' ';

for (int i = 0; i < str.length(); i++)

{

//Get a char and go through entire string to determine how many times that char occurs

char x = str.charAt(i);
int c = 0;

for (int j = str.indexOf(x); j != -1; j = str.indexOf(x, j + 1))

{

c++;

}

if (c > highestFreq)

{

highestFreq = c;

mostFreqChar = x;
}

}

return mostFreqChar;
}

关于java - 给定一个字符串作为输入,返回在字符串中出现次数最多的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32319463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com