I am trying to make an algorithm that will find the index of a given substring (which I have labeled pattern
) in a given String
(which I have labeled text
). This method can be compared to String.indexOf(String str)
. In addition to general feedback, I'm curious what the time complexity of my method is, and would appreciate if someone can help me figure it out.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
public class SubstringSearch {
public static void main(String[] args) {
String text = "This is a test String";
String pattern = "is a";
int index = search(pattern, text);
System.out.println(index);
}
private static int search(String pattern, String text) {
int patternLength = pattern.length();
int textLength = text.length();
Set<Integer> set = new HashSet<>(textLength);
List<Integer> addList = new ArrayList<>(textLength);
for (int i = 0; i < textLength; i++) {
set.add(0);
for (Integer index : set) {
if (pattern.charAt(index) == text.charAt(i)) {
addList.add(index + 1);
}
}
set.clear();
set.addAll(addList);
if (set.contains(patternLength)) {
return i - patternLength + 1;
}
}
throw new NoSuchElementException();
}
}
addList
norset
. Hint 2: the complexity is \$ \mathcal{O}(n^2) \$ \$\endgroup\$ – Miguel Avila Jan 25 at 2:07Set
and theList
? \$\endgroup\$ – a p Jan 25 at 2:43pattern[i] == text[i] && pattern[i + pattern.length - 1] == text[i + text.length - 1]
using a for conditioni < pattern.length / 2
. It is less probable for human words to coincide in such a way more than 3 end-to-end comparisons with equal lenght. This is for single mathch not substrings, still you may extend the reasoning. Respect to the complexity of this new algorithm it could be in average \$O(n)\$ and in worst case \$O(n^2)\$ \$\endgroup\$ – Miguel Avila Jan 25 at 2:58