I have a method I created which is a custom indexOf()
. This code seems ugly to me so I was wondering if anyone could recommend a cleaner and perhaps faster implementation of my method.
public static int myIndexOf(char[] str, char[] substr, int index) {
if (str == null) {
throw new NullPointerException();
}
if (substr.length > str.length) {
return -1;
}
if (substr.length == 0 && index >= str.length) {
return str.length;
}
if (substr.length == 0 && index >= 0) {
return index;
}
if (substr.length == 0 && index < 0) {
return 0;
}
if (substr.length == 0 && str.length == 0 ) {
return 0;
}
int[] found = boyerMoore(str, substr);
for (int i : found) {
if (i >= index) {
return i;
}
}
// can not found substring after index
return -1;
}
// Don't necessarily need any modification for this method. But for those who are interested
Boyer Moore:
public static int[] boyerMoore(char[] str, char[] substr) {
// index array of indexes of found substrings
// initialize
int indexCounter = 0;
int[] subStringIndex = new int[str.length];
for (int c = 0; c < str.length; c++) {
subStringIndex[c] = -1;
}
// character set ASCII
int characterSet = 256;
// initialize
int[] charSet = new int[characterSet];
for (int a = 0; a < characterSet; a++) {
charSet[a] = -1;
}
for (int b = 0; b < substr.length; b++) {
charSet[substr[b]] = b;
}
int skip;
for (int i = 0; i <= (str.length - substr.length); i += skip) {
//System.out.print(i);
skip = 0;
for (int j = substr.length - 1; j >= 0; j--) {
if (substr[j] != str[i + j]) {
skip = Math.max(1, j - charSet[str[i + j]]);
break;
}
}
if (skip == 0) {
// increment next value in String
skip++;
// add found substring (beginning index)
subStringIndex[indexCounter] = i;
indexCounter++;
// this last bit is used if Boyer Moore stops searching after first instance is found
// return i;
}
}
return subStringIndex;
// This bit is used when Boyer Moore is stops after the first instance in found
// cannot be found
// return str.length;
}
in[]
if more than one instance of the substring is found \$\endgroup\$