Brute force string matching systematically checks if the pattern matches a substring at each position in the text. It aligns the pattern with the text and compares characters one by one. If a mismatch occurs, it shifts the pattern to the right by exactly one position and starts comparing again.
def brute_force_match(text, pattern):
n = len(text)
m = len(pattern)
for i in range(n - m + 1):
j = 0
while j < m:
if text[i + j] != pattern[j]:
break
j += 1
# Pattern matched completely
if j == m:
return i
return -1
function bruteForceMatch(text, pattern) {
const n = text.length;
const m = pattern.length;
for (let i = 0; i <= n - m; i++) {
let j;
for (j = 0; j < m; j++) {
if (text[i + j] !== pattern[j]) {
break;
}
}
// Match found!
if (j === m) {
return i;
}
}
return -1;
}