This algorithm look开发者_Go百科s through a string and tries to find another string. The logic is simple, I guess. Though, I need help finding it's complexity.
int find(string mString, string lookUp)
{
int i, z, j, m = mString.size(), n = lookUp.size(), broken = 0, st = 0;
for(j = 0, i = 0; i < m; i++)
{
if(mString[i] == lookUp[j])
{
if(broken)
{
//go back and see if we're on the good path
broken = 0;
for(z = 0; z < j; z++)
{
if(broken) break;
if(mString[i-z] == lookUp[j-z])
broken = 0;
else
broken = 1;
}
if(!broken) st = i - j + 1;
}
if(j + 1 != n)
j++;
}
else
broken = 1;
}
return st;
}
Can somebody please help me?
Thank you.
When dealing with big-O and loops, I ask myself the question:
How many times, at most, can each loop run?
In your example,
- The outer loop will run, at most, `m` times.
- The inner loop will run, at most, `n` times.
- For each iteration of the outer loop, the inner loop will run, at most, `n` times
Does this help clarify your thinking?
O(n^2) is the final complexity of this algorithm.
精彩评论