This is a problem from CodeWar.
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
EX: "abba" -> 2, "aabBcde" -> 2.
Here is my solution in Java:
public class CountingDuplicates {
public static int duplicateCount(String text) {
String textLower = text.toLowerCase();
char[] charArray = textLower.toCharArray();
String uniqueRepeats = ""; //Will keep track of unique repeats.
int count = 0;
for(int i = 0; i < charArray.length - 1; i ++) {
String restOfString = textLower.substring(i + 1);
//Convert single char to String to be used in method.
String character = Character.toString(charArray[i]);
//If not in uniqueRepeats, check if it is a repeat.
if(!uniqueRepeats.contains(character)) {
if(restOfString.indexOf(character) != -1) {
//If it is a repeat, increase count and concat it to uniqueRepeats
count++;
uniqueRepeats += character;
}
}
}
return count;
}
}
Some improvements that I can think of is using a HashMap to store the repeats so that I do not have to create a new string object for every repeat If you guys have any suggestions on code readability, code structure, or better implementation for this problem, please leave me a comment. Thank you! EDIT - Here is the link to the problem: https://www.codewars.com/kata/counting-duplicates/train/java