java,如何在不重复的情况下查找字符串中的字母数量

java, how to find the amount of letter in a string without repeats

我正在尝试构建一个函数,它获取一串字母,并打印字符串中每个字母的数量。 例如: 输入:字符串 = "aaabbaccxyxyx" 输出:4a2b2c3x2y

这是我想出的:

public class Q1 {
    public static String numLetters(String s){
        String end = new String();
        int counter = 0;
        char c,d;
        for(int i=0; i<s.length();i++){
            c = s.charAt(i);
            for(int j=0; j<s.length();j++){
                d = s.charAt(j);
                if(c == d){
                    counter++;
                }
            }
            end = end + counter+c;
            counter = 0;
        }

        return end;
    }

但是,这是输出:4a4a4a2b2b4a2c2c3x2y3x2y3x 很多重复..

任何帮助如何使它正确? 请记住,该函数需要 return 一个 字符串 ,而不仅仅是打印出来。 谢谢! =)

试试这个:

int count = StringUtils.countMatches("a.b.c.d", ".");

我会制作一个 int 数组来保持字符串中每个字母的计数。因为有26个字母,数组的length应该是26:

public static String numLetters(String s) {
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        count[(int)(c - 'a')]++;
    }
    String ans = "";
    for (int i = 0; i < 26; i++) {
        if (count[i] != 0) {
            ans += String.valueOf(count[i]) + (char)(i + 'a');
        }
    }
    return ans;
}

一个简单的变体可能如下所示:

public static String countChars(String arg) {
    String res = "";
    boolean[] counted = new boolean[arg.length()];
    for (int i = 0; i < counted.length; i++) {
        if (!counted[i]) {
            char c = arg.charAt(i);
            int counter = 1;
            for (int j = i + 1; j < counted.length; j++) {
                if (arg.charAt(j) == c) {
                    counter++;
                    counted[j] = true;
                }
            }
            res += counter + "" + c;
        }
    }
    return res;
}

如果你想保留原来的结构,我建议使用 StringBuilder 这样你就可以删除你已经看到的字符。如果你删除了一个字符,你必须调整你的索引 ij.

public static String numLetters(String str){
    StringBuilder s = new StringBuilder(s);
    String end = new String();
    int counter = 0;
    char c,d;
    for(int i=0; i<s.length();i++){
        c = s.charAt(i);
        for(int j=0; j<s.length();j++){
            d = s.charAt(j);
            if(c == d){
                s.deleteCharAt(j);
                if (i >= j) i--;
                j--;
                counter++;
            }
        }
        end = end + counter+c;
        counter = 0;
    }

    return end;
}