Skip to content

Instantly share code, notes, and snippets.

@KevinVR
Created April 5, 2021 12:40
Show Gist options
  • Save KevinVR/48d351cae7e28a52218fc10de576a80a to your computer and use it in GitHub Desktop.
Save KevinVR/48d351cae7e28a52218fc10de576a80a to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
// Let's develop our first solution
public class CountingDuplicates {
public static int duplicateCount(String text) {
// We need to count the amount of characters which have duplicates (not the amount of duplicates)
int totalCharsWithDupes = 0;
// Keep an array of characters which have already been counted towards the totalDupes counter
// Since we want to count the amount of characters which have duplicates
// Not the actual amount of total duplicates
ArrayList<Character> charsCountedForDupes = new ArrayList();
// Let's iterate over every character, and see whether it has dupes
for (int x = 0; x < text.length(); x++) {
// Get the lowercase character, to be case-insensitive
Character currentChar = Character.toLowerCase(text.charAt(x));
// Check if the current string has it as duplicate
// We can start from our current position in the string (+ 1, for not counting the same character)
// Previous characters have already been checked
for (int y = x + 1; y < text.length(); y++) {
// Get the second character to lowercase for a fair case-insensitive comparison
Character secondChar = Character.toLowerCase(text.charAt(y));
// If the character is the same, it is a duplicate
if (currentChar == secondChar) {
// It's a duplicate
// Did we already count this character towards the duplicates counter?
// We don't want to count the same character twice
if (!charsCountedForDupes.contains(currentChar)) {
// New duplicate! Increment total and add to the counted list
// to avoid counting it again in the future
charsCountedForDupes.add(currentChar);
totalCharsWithDupes++;
}
}
}
}
// Return the amount of characters which have duplicates
return totalCharsWithDupes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment