Java 如何用字符串计算重复数?
我是编程新手,我是用字符串开发的,我还没有用哈希映射,我唯一的问题是最后一个字母。例如,最后一个字母s值包含2,而不是1。我该怎么做Java 如何用字符串计算重复数?,java,Java,我是编程新手,我是用字符串开发的,我还没有用哈希映射,我唯一的问题是最后一个字母。例如,最后一个字母s值包含2,而不是1。我该怎么做 public static void main(String[] args) { String word = "Chris", curr_char, next_char; int length_string = word.length(), count = 0; char end_
public static void main(String[] args) {
String word = "Chris",
curr_char,
next_char;
int length_string = word.length(),
count = 0;
char end_letter = word.charAt(word.length()-1);
String end = Character.toString(end_letter);
for(int index = 0; index < word.length(); index++)
{
curr_char = word.substring(index, index+1);
for(int next_index = 0;next_index<word.length(); next_index++)
{
next_char = word.substring(next_index, next_index+1);
if (curr_char.equalsIgnoreCase(next_char))
{
count = 1;
}
if(curr_char.contains(end))
{
count = count + 1;
}
}
System.out.println(word.charAt(index) + " " + count);
}
}
publicstaticvoidmain(字符串[]args){
String word=“Chris”,
库尔查,
下一个字符;
int length_string=word.length(),
计数=0;
字符结束字母=word.charAt(word.length()-1);
字符串结束=字符.toString(结束字母);
for(int index=0;index 对于(int next_index=0;next_index,此代码现在运行良好:
public static void main(String args[]) {
String word = "Chris" , curr_char , next_char;
int length_string = word.length();
char end_letter = word.charAt(word.length()-1);
String end = Character.toString(end_letter);
for(int index = 0; index <word.length(); index++)
{
int count = 0; //resetting the value of count every time
curr_char = word.substring(index, index+1);
for(int next_index = 0;next_index<word.length(); next_index++)
{
next_char = word.substring(next_index, next_index+1);
if (curr_char.equalsIgnoreCase(next_char))
{
count = count + 1;
//if any character repeats it increase the value of count
}
}
System.out.println(word.charAt(index) + " " + count);
}
}
publicstaticvoidmain(字符串参数[]){
字符串word=“Chris”,curr\u char,next\u char;
int length_string=word.length();
字符结束字母=word.charAt(word.length()-1);
字符串结束=字符.toString(结束字母);
对于(int index=0;index您的算法逻辑中存在一些问题。该算法无法处理诸如“Chriss”或“chcris”之类的字符串。输入字符串“Chriss”的输出将
C1
h 1
r1
i 1
s2
S1
另外,你有2次迭代,这使得算法效率不高。一个高效的算法应该花费更少的时间(高速)和更少的空间(更少的内存)
上面的问题通常通过使用一个大小为26的整数数组(比如charArrayCount)来解决,因为英文字母表中有26个字母。这个整数数组的每个元素代表字母表中的一个字符,用于计算它在字符串中出现的次数。您可以迭代字符串中的每个字符并使用f奥穆拉
charArrayCount[25 - ('z' - ch)] += 1;
其中“ch”将是字符串中的一个字符。然后,您可以遍历数组“charArrayCount”,并获得大于1的值。您必须考虑大写和小写字符
在这种情况下,只需对字符串进行1次迭代&不管字符串有多长,比如说1000个字符,都只为26个元素的整数数组创建空间
试试这个,看看是否有帮助。最后一个字母,例如s,值包含2,而不是1,我不确定我是否理解该部分…请尝试提出一个完整的问题解释。不清楚你在问什么。请提供更多上下文。欢迎这样做。请发布格式正确的代码,因为很难重新发布现在就按照格式化的方式进行广告你想让你的代码做什么?…打印一个字符在一个字符串中存在多少次?!你做了什么,为什么,这至少应该通过指出已更改的代码来解释。OP也需要从中学习。请更完整地回答现在就测试代码,我已经提到了注释,这样做吧读一下