user3628651
user3628651

Reputation: 43

Counting the number of unique letters in a string

I have to write code that counts how many unique letters are in a string: e.g

"aabbcdefff"

This will return 6 as there are 6 different letters in the string. Currently I have the code:

  String letters = ("aabbcdefff");              
  char temp = ' ';
   for (int i = 0; i < letters.length(); i++){
      temp = inp.charAt(i);
      if (temp != ' ') {   //doesnt count spaces as letters
        alphabetSize = alphabetSize+1;
          for (int j = 0; j < inp.length(); j++){
            tempInp = tempInp.replace(temp,' ');
        }
      }
    }   

The idea of this code is that it should when detecting a letter, replace all instances of it with a space. When i run this code however, it just gives me the length of the string. What am i doing wrong? Is there another more elegant way to do this?

Thanks for your help.

Upvotes: 2

Views: 2582

Answers (5)

user2472819
user2472819

Reputation: 123

One way of doing this would be converting the string to an array and then using the following method:

    String s = "aabbcdefff";

    char[] charArray = s.toCharArray();

    ArrayList<Character> al = new ArrayList<Character>();


    for(char c : charArray){
        if(al.contains(c)){
            al.remove((Character)c);
        }else{
            al.add(c);
        }
    }

What ever is left in the array list 'al' are duplicates. The advantage of this method is that it has O(n) runtime

Upvotes: 0

user3656431
user3656431

Reputation:

You can easily find it using Linq service.

Please add using System.Linq; Namespace.

string str = "TestTest";
int cnt = str.ToLower().ToCharArray().Where(w => w != ' ').Distinct().Count();

Upvotes: 1

isnot2bad
isnot2bad

Reputation: 24444

It's a one-liner with Java 8 streaming API:

long numberOfDistinctChars = s.chars().distinct().count()

Upvotes: 2

MrYo
MrYo

Reputation: 1817

You can do it easily by using Java collection (Set).

Set<Character> result = new HashSet<Character>();

    String letters = ("aabbcdefff");              
       for (int i = 0; i < letters.length(); i++){
          result.add(letters.charAt(i));
        }   

Your final result is in result set and it is always unique.

Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html

Thanks.

Upvotes: 0

PKlumpp
PKlumpp

Reputation: 5233

You are fine by just using a Set.

Loop over your string, and add each letter to your set. afterwards, check length of your set, and your done.

Upvotes: 6

Related Questions