有 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_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);   
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您的算法逻辑中存在一些问题。该算法不适用于“Chriss”或“chcris”等字符串。输入字符串“Chriss”的输出将是

    C1
    h1
    r1
    i 1
    s2
    S1

    此外,您有2次迭代,这使得算法效率不高。一个高效的算法应该花费更少的时间(高速)&;更少的空间(更少的内存)

    上述问题通常通过使用一个整数数组来解决,比如说charArrayCount,大小为26,因为英语字母表中有26个字母。此整数数组的每个元素表示字母表中的一个字符&;用于计算它在字符串中出现的次数。您将遍历字符串中的每个字符&;使用公式

    charArrayCount[25 - ('z' - ch)] += 1;  
    

    其中“ch”是字符串中的一个字符。然后可以遍历数组“charArrayCount”&;获取这些值>;1.您必须处理大写字母和大写字母;小写字符

    在本例中,您只有一次对字符串&;的迭代;不管字符串有多长,比如说1000个字符,都只为26个元素的整数数组创建空间

    试试这个&;看看是否有帮助

  2. # 2 楼答案

    此代码现在运行良好:

    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);   
    }
    
    }
    

    测试一下这个