-2

I want to count tokens in word which don't duplicate .

Example:
aabbcc
abc

Result:
0
3

I must use StrTokazizer or sth like that

Cœur
  • 37,241
  • 25
  • 195
  • 267
MOnasz
  • 99
  • 1
  • 2
  • 8

2 Answers2

1

This will work:

public int getUniqueTokensCount(String input)
{
    Set<Character> set = new HashSet<Character>();
    Set<Character> dups = new HashSet<Character>();

    for (char c: input.toCharArray())
        if (!set.add(c))
            dups.add(c);

    set.removeAll(dups);
    return set.size();
}

We collect all characters from the string in set and, if it is a duplicate, add the character to dups. When all the string has been parsed, we remove from set (which contains all individual characters) all found duplicates. The number of unique tokens is then this set's size.

This relies on the fact that a Set's .add() operation will return false if the element to add is already present.

fge
  • 119,121
  • 33
  • 254
  • 329
1

If you are using Java,the following should work:

public class UniqueTokenCounter{
  public static void main(String[] args) 
  {
    Arraylist<String> tokens = new ArrayList<String>();

    int uniqueCount=0;

    StringTokenizer stringTokenizer = new StringTokenizer("a b c b d");

    while(stringTokenizer.hasMoreTokens())
    {
       tokens.add(stringTokenizer.nextToken())
    }

    boolean unique=true;
    for(String uniqueToken : tokens) 
    {
       for(String token : tokens) 
       {
          if(uniqueToken.equals(token))
            unique=false;
       }
       if(unique)
          uniqueCount++;
       else
          unique=true;
    }
    //print uniqueCount
  }
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Priyanka.Patil
  • 1,177
  • 2
  • 15
  • 34