获取字符数

Get the number of characters

我需要分别计算每个重复字符的数量....我已经尝试过..但它 returns 只有唯一字符数...

输入:

SSDDVVDSSS

输出:

S - 5
D - 3
V - 2

这是我的代码

public class q2 {

public static void main(String[] args) {

   System.out.println(countUniqueCharacters("SSDDVVDSSS"));
}


public static int countUniqueCharacters(String input) {
boolean[] isItThere = new boolean[Character.MAX_VALUE];
for (int i = 0; i < input.length(); i++) {
    isItThere[input.charAt(i)] = true;
}

int count = 0;
for (int i = 0; i < isItThere.length; i++) {
    if (isItThere[i] == true){
        count++;
    }
}

return count;
}


}
public static void main(String[] args) {
        String str = "SSDDVVDSSS";
        int counts[] = new int[(int) Character.MAX_VALUE];

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            counts[(int) c]++;
        }

        for (int i = 0; i < counts.length; i++) {
            if (counts[i] > 0)
                System.out.print((char) i + "-" + counts[i] + "\n");
        }
    }

你的最后一个 'for' 循环遍历计数器数组并计算它包含多少具有真实值的条目。 因此你得到了独特的字符数。

试试这个:

public class q2 {

public static void main(String[] args) {

    countUniqueCharacters("SSDDVVDSSS");
}


public static void countUniqueCharacters(String input) {


    Map<Character,Integer>  map = new HashMap<Character, Integer>();

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

        if (map.get(input.charAt(i)) == null){
             map.put(input.charAt(i),1);
        }
        else{
            map.put(input.charAt(i),map.get(input.charAt(i))+1);
        }
    }

     System.out.print(map);
}

}

以下是您的代码中的问题:

  1. 您正在定义 65535 大小的数组,这对于 26 个字符来说是不必要的。
  2. 您定义了布尔数组,其中每个元素将存储两个值,true 或 false,如果您需要查看字符串中是否存在字符但不适合您的算法,这是非常需要的。
  3. 您已经共享了计数器变量,它将为您提供字符串的长度,即您的字符串中有多少个字符,这不是您所需要的。

您可以通过多种方式解决此问题:

  • 使用索引为 0 - 26 的 int 数组来维护字符 A-Z 的计数,最后打印计数:

        public static void main(String[] args) {
        int[] counts = countUniqueCharacters("SSDDVVDSSS");
        for (int i = 0; i < counts.length; i++) {
            if (counts[i] != 0) {
                System.out.println("char " + ((char) ('A' + i)) + " repeated " + counts[i] + " times");
            }
        }
    }
    
        public static int[] countUniqueCharacters(String input) {
        int[] counts = new int[26];
        for (int i = 0; i < input.length(); i++) {
            counts[input.charAt(i) - 'A']++;
        }
        return counts;
    }
    
  • 另一种方法是使用 map,以字符为键,以 int 为值,表示该字符重复的次数。