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...
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.
Algorithm is very simple:
After that your set contains only unique characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With