Counting unique characters in a String given by the user

前端 未结 12 1401
情书的邮戳
情书的邮戳 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.

    0 讨论(0)
  • 2021-02-15 18:00

    Unique Characters In A String:

    This is a basic Java interview subject, where the interviewer wants to check the knowledge of HashSet or indexOf(in case of Java 7) . Let's take up a question. Let's say the interview tells you to
    Check if the String is unique : HashSet ensures uniqueness ,In other words , every object in the HashSet presents only once. Hence, we will use HashSet.

    import java.util.HashSet;
    import java.util.Set;
    
    public class Abc {
    public static void main(String[] args) {
        String a = "Gini";
        String aa = a.toLowerCase();
           if(  isUnique(aa)   ) {
                  System.out.println("All characters are unique");
           }else {
               System.out.println("All characters  are not unique");
           }
    }
    public static boolean isUnique(String a ) {
        Set< Character> set = new HashSet<>();
        char[] charArray =a.toCharArray();
        for(Character ch :charArray) {
            if(!set.add(ch)) {
                return false;
            }//if
        }//foreach
            return true;
    }
    }
    

    The output in case of GINI will be : All characters are not unique

    Now, the count of the unique characters. Here also we will use HashSet because of the uniqueness.

    import java.util.HashSet;
    
    public class practice11 {
    public static void main(String[] args) {
        String a = "Gini";
        String aa = a.toLowerCase();
        System.out.println(countUniqueCharacters(aa));  
    }
    public static int  countUniqueCharacters(String a) {
        char[] charArray = a.toCharArray();
    
        HashSet<Character> set = new HashSet<Character>();
    
        for(int i = 0 ; i< charArray.length ; i++) {
    
             set.add(charArray[i]);
        }//for
        return   set.size() ;//This will give 3
    }
    }
    

    The output for Gini will be 3 (Gin will be considered) .

    indexOf Method : indexOf() returns the index of first occurrence of the character and then we are comparing with -1.

    public class Abc {
    public static void main(String[] args) {
        String a = "Gini";
        String aa = a.toLowerCase();
        String t = " ";
        for (int i = 0; i < aa.length(); i++) {
                int  pp =   aa.charAt(i) ;
    
            if(t.indexOf(aa.charAt(i))  ==  -1  ) {
                t = t + aa.charAt(i);
            }//if
    
    
        }//for
    
        System.out.println(t );// This will give => gin
        System.out.println(t.length()); // this will give 3
    }//main
    }//end
    

    In Java 8, this is extremely easy. We just have to use chars().distinct().count(). But the return type will be long.

    class Abc{
        public static void main(String[] args) {
            String a = "Gini";
            String aa = a.toLowerCase();
            System.out.println(  countUnique(aa));
        }
    
        private static long  countUnique(String aa) {
            // this will give 3(gin. another i will be not be counted as we have used distinct())
             return  aa.chars().distinct().count() ; 
        }
    }
    

    Another classic Interview Question : Find the First non repeating character in the String OR the First Unique Character in a String. This problem can be solved using the knowledge of HashMap.

    class Abc{
        public static void main(String[] args) {
              String a = "GinaRani" ;
    // Output will be G
              System.out.println( firstNonRepeatingCharacter(a) );
    
        }//main
        public static Character firstNonRepeatingCharacter(String a){
          Map<Character, Integer> map = new HashMap<>();
            char[] charArray = a.toCharArray();
            for(    Character  ch   :     charArray){
                   if( map.containsKey(ch)   )   {
                        map.put(ch, map.get(ch) +1 ) ;
                   } else{
                       map.put(ch, 1);
                   }
            }//for
    
            // 1st non repeating character
    
            for( int  i = 0 ; i < a.length(); i ++ ){
                 char chh = a.charAt(i);
                 if(  map.get(chh) == 1 ){
                     System.out.println("first non repeating character in the String is  : ");
                       return chh ; 
                 }//if
            }//for
    
            return null; 
    
        }//firstNonRepeatingCharacter
    }//end
    

    We will do this with the help of list comprehension in Python. We are not using set() operator. In Python :

    string = 'GiniGinaProtijayi'
    
    unique = []
    
    [ unique.append(ch)  for ch in string if ch not in unique ]
    lengthofUniqueCharacters = len(unique)
    print("length of Unique Characters => " ,lengthofUniqueCharacters)
    print("as a list => ",unique)
    print("as a string => " , ''.join(unique))
    

    Just to print out the distinct characters in Java 8:

    public class Test5 {
        public static void main(String[] args) {
            String a = "GinaGini";
    
            String aa = a.chars().distinct()
                    .collect(StringBuilder::new, 
                            StringBuilder::appendCodePoint, 
                            StringBuilder::append)
                    .toString();
            System.out.println(aa);//Gina
    
        }// main
    
    }
    
    0 讨论(0)
  • 2021-02-15 18:03

    Using Java 8 you could do the following:

    public static long countUniqueCharacters(String input) {
        return input.chars()
                .distinct()
                .count();
    }
    

    This creates an IntStream of chars, then takes only distincts values and then counts the number of occurences.

    0 讨论(0)
  • 2021-02-15 18:10
    public static long calculateDistinctSubStringSum(String text) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        char[] charAarry = text.toCharArray();
        for (int i = 0; i < charAarry.length; i++) {
            map.put(charAarry[i] + "", 1);
        }
        return map.size();
    
    }
    

    This is what I did to calculate but I am still looking for any fast way. If anyone knows please answer.

    0 讨论(0)
  • 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<Character> unique = new ArrayList<Character>();
         for( int i = 0; i < arg.length(); i++)
             if( !unique.contains( arg.charAt( i ) ) )
                 unique.add( arg.charAt( i ) );
         return unique.size();
     }
    
    0 讨论(0)
  • 2021-02-15 18:13
    public static int countUniqueChars (String buf) {
        HashSet<Character> hash = new HashSet<>();
        buf = buf.toUpperCase();
        for (int i = 0; i < buf.length(); i++)
            hash.add(buf.charAt(i));
        return hash.size();
    }
    
    0 讨论(0)
提交回复
热议问题