Create a function: find index of first non-repeating lowercase letter; return -1 if none.
The NonRepeatingFinder
class finds the index of the first non-repeating character in a given string by iterating through each character and checking for duplicates.
class NonRepeatingFinder {
String inputString;
int stringLength;
public NonRepeatingFinder(String inputString) {
this.inputString = inputString;
this.stringLength = inputString.length();
}
public int findFirstNonRepeatingIndex() {
int duplicatesCount;
// Iterate through each character in the string
for (int currentIndex = 0; currentIndex < stringLength; currentIndex++) {
duplicatesCount = 0;
// Compare the current character with all other characters
for (int otherIndex = 0; otherIndex < stringLength; otherIndex++) {
// If a duplicate character is found
if (currentIndex != otherIndex && inputString.charAt(currentIndex) == inputString.charAt(otherIndex)) {
duplicatesCount++;
break;
}
}
// If no duplicates found for the current character, return its index
if (duplicatesCount == 0) {
return currentIndex;
}
}
// Return -1 if no non-repeating character is found
return -1;
}
}
The NonRepeatingCharacterFinder
class demonstrates the usage of NonRepeatingFinder
to identify and print the index of the first non-repeating character in a given string.
public class NonRepeatingCharacterFinder {
public static void main(String[] args) {
String givenString = "abcdcaf";
NonRepeatingFinder finder = new NonRepeatingFinder(givenString);
int firstNonRepeatingIndex = finder.findFirstNonRepeatingIndex();
System.out.println(firstNonRepeatingIndex); // Prints the index of the first non-repeating character
}
}