Counting unique characters in a String given by the user

前端 未结 12 1429
情书的邮戳
情书的邮戳 2021-02-15 17:42

I have to write a program that counts the uniques characters in a String given by the user. For example \"abc\" returns 3 and \"aabbccd\" returns 4. I am not allow to use advan

12条回答
  •  忘了有多久
    2021-02-15 17:58

    Here another solution:

    public static int countUniqueCharacters(String input) {
        String buffer = "";
        for (int i = 0; i < input.length(); i++) {
            if (!buffer.contains(String.valueOf(input.charAt(i)))) {
                buffer += input.charAt(i);
            }
        }
        return buffer.length();
    }
    

    The first occurance of each character is stored in buffer. Therefore you have of all characters one in buffer, therefore buffer.length() delivers the count you need.

提交回复
热议问题