int bruteForce(string T, string P, int s) // s = start position
{
int n = T.length(), m = P.length();
int j = 0; // Start match with character pos = 0
while ( s+(m-1) < n ) // Last char pos in P is valid character in T
{
if ( P[j] == T[s+j] )
{
j++; // Continue with next character
if ( j == m )
return(s); // Pattern found at pos s
}
else
{
s += 1; // Use next shift position
j = 0; // reset to 1st char in pattern to match
}
}
return -1; // Pattern not found
}
|
int bruteForce(string T, string P, int s) // s = start position
{
int n = T.length(), m = P.length();
int j = m-1; // Start match with character pos = m-1
while ( s+(m-1) < n ) // Last char pos in P is valid character in T
{
if ( P[j] == T[s+j] )
{
if ( j == 0 )
return(s); // Pattern found at pos s
j--; // Continue with next character
}
else
{
s += 1; // Use next shift position
j = m-1; // reset to 1st char in pattern to match
}
}
return -1; // Pattern not found
}
|
DEMO: brute-force2.cc