Counting unique characters in a String given by the user

前端 未结 12 1408
情书的邮戳
情书的邮戳 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条回答
  •  -上瘾入骨i
    2021-02-15 18:13

    If your stuck on Java 7, you can use an ArrayList and just add unique values to it, then return the size of the ArrayList, which should always work even if the count is zero.

     import java.util.ArrayList;
    
     public int getUniqeCount( String arg )
     {
         ArrayList unique = new ArrayList();
         for( int i = 0; i < arg.length(); i++)
             if( !unique.contains( arg.charAt( i ) ) )
                 unique.add( arg.charAt( i ) );
         return unique.size();
     }
    

提交回复
热议问题