I am only a second semester CS student and can't use any of the well known efficient substring search algorithms. I need to implement the indexOf method with the following method signature:
int indexOf(String str, String pattern)
which returns the index of the first location at which pattern appears as a substring of str.
This is what I attempted:
First I created an overloaded method index of with the signature indexOf(String str, char ch, int startIndex)
that returns the index of the first location of char or -1 otherwise.
private int indexOf(String str, char ch, int startIndex) {
for(int i = startIndex; i < str.length(); i++)
if(str.charAt(i) == ch) return i;
return -1;
}
Now I write the method that searches for a substring (pattern
).
private int indexOf(String str, String pattern) {
int headIndex = indexOf(str, pattern.charAt(0), 0);
int tailIndex = indexOf(str, pattern.charAt(pattern.length() - 1), 0);
if(headIndex == -1 || tailIndex == -1) return -1; // no substring match
while(true) {
int j = 0;
for(int i = headIndex; i <= tailIndex; i++)
if(str.charAt(headIndex) != pattern.charAt(j++)) { //if substring does not match then compute a new head and tail Index
headIndex = indexOf(str, pattern.charAt(0), headIndex);
tailIndex = indexOf(str, pattern.charAt(pattern.length() - 1), tailIndex);
j = 0;
i = headIndex + 1;
if(headIndex == -1 || tailIndex == -1) return -1;
break;
}
if(headIndex >= 0) return headIndex;
}
}
I believe I am close but calls like indexOf("Hellolo", "lo")
returns 2 instead of 3. I'm trying to figure out where I went wrong with my logic and need help in doing so.
I am not allowed to use any special string methods except length.