I am using the following brute force algorithm for searching a string inside another string.
As I know, the number of comparisons is (n-m+1)*m
in the worst case, but the right answer for time complexity is supposed to be O(n*m)
.
To get this answer, I do the following transformations:
(n-m+1)*m = (n+1) * m - m^2 = O(n*m) - m^2
How do you get O(n*m)
from here?
Where did -m^2
go?
Brute force algorithm:
NAIVE-STRING-MATCHER
n = T.length
m = P.length
for s = 0 to n - m
if P[1...m] == T[s+1...s+m]
print s