Counting unique characters in a String given by the user

前端 未结 12 1398
情书的邮戳
情书的邮戳 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 18:22

    It is extremely easy :)

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

    Example for input "aab"

    First for-cycle goes 3 times, each time for one char.

    Value of "a" is 97, so it turns isItThere[97] to true, then second "a" is involved, which is doing the same, isItThere[97] is set to true again (hence changing nothing).

    After that "b" is involved, value of char "b" is 98, therefore isItThere[98] is set to true.

    And then you have second for-cycle, where you cycle through the all isItThere array. If you find any true statement, you increment count. In our case, you find isItThere[97] and isItThere[98] as true statement, it means you increment twice and returning 2.

提交回复
热议问题