Reputation: 6241
Θ(n+m)
? n
is size of i_StringForSearch
, m
is size of i_SubStringToFind
.
2.Is there any program which is recommended to check time complexity of a given code, I prefer a free tool which is well recognized.
Thank you
public static boolean isSubstring(String i_StringForSearch, String i_SubStringToFind)
{
int strForSearchIndex = 0;
int subStrToFindIndex = 0;
boolean endOfStringToSearch = false;
boolean foundSubString = false;
boolean isThereASequenceOfMatching = false;
while(!endOfStringToSearch && !foundSubString)
{
if(strForSearchIndex == i_StringForSearch.length())
{
endOfStringToSearch = true;
}
else if(i_StringForSearch.charAt(strForSearchIndex) == i_SubStringToFind.charAt(subStrToFindIndex))
{
isThereASequenceOfMatching = true;
if(subStrToFindIndex == i_SubStringToFind.length() -1 )
{
foundSubString = true;
}
subStrToFindIndex++;
strForSearchIndex++;
}
else if(i_StringForSearch.charAt(strForSearchIndex) != i_SubStringToFind.charAt(subStrToFindIndex))
{
if(isThereASequenceOfMatching)
{
subStrToFindIndex = 0;
isThereASequenceOfMatching = false;
}
strForSearchIndex++;
}
}
return foundSubString;
}
Upvotes: 0
Views: 316
Reputation: 178471
Answering your question: yes, the algorithm is O(n+m)
. Each
iteration increases strForSearchIndex
, so there are at most n
iterations. [this is assuming i_StringForSearch.length()
is done
in O(1)
, which is usually true].
The algorithm is wrong with the counter example of isSubstring("aaab","aab") == false
.
You might want to have a look on Knuth Morris Pratt algorithm and/or Rabin-Karp algorithm and/or Aho-Corasick Algorithm
Upvotes: 1