Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to check for duplicate characters in a string?

I need to write a function that checks a string for duplicate values and returns the count of unique characters. If the count is greater than 3, it should return true. If the count is less than 3, it should be false. Here is what I have been trying (notice I'm new to java)

private boolean isFormatValid(String password) {
    CharSequence inputStr = password;
    int length = inputStr.length();
    int numberDups = 0;

    for(int i=0; i < length; ++i) {
        Pattern pattern = Pattern.compile("(.)(?=.*?\1){1,20}");
        Matcher matcher = pattern.matcher(inputStr);
        numberDups += 1;
    }
    if (numberDups < 3) {
        return false;
    }
    return true;
}

I was trying to use a regex because it was suggested it might be easier. But if I can accomplish this without a regex I'd be happier.

Is this what is meant?

private boolean isFormatValid(String password) {
    int length = inputStr.length();
    int numberChars = 0;

    for(int i=0; i < length; ++i) {
                int index = password.indexOf(i);
        CharArray[i] = charAt(i);   
    }
}

I feel this isn't even close to being right...

like image 386
Rich Avatar asked Oct 28 '11 14:10

Rich


2 Answers

You're pretty much there. Rather than use a regular expression, you can use the index: i to index into the String and read a particular character using charAt(int).

You then need a data structure to keep track of the number of occurences of each character. I suggest using a HashMap for this whereby the map key is the Character you've read and the map value is the Integer count of the number of occurences.

like image 131
Adamski Avatar answered Oct 19 '22 22:10

Adamski


Algorithm is very simple:

  1. Split string into array of characters
  2. Add all these characters to Set (HashSet).

After that your set contains only unique characters.

like image 29
mishadoff Avatar answered Oct 20 '22 00:10

mishadoff