less than 1 minute read

Brute Force

def bruteForce(text, pattern):
    n = len(text)
    m = len(pattern)
    i = j = 0
    while i < n and j < m:
        if text[i] != pattern[j]:
            i = i - j
            j = -1
        i += 1
        j += 1
    if j == m:
        return i - m
    return -1

a = 'pineapple'
b = 'apple'
print(bruteForce(a, b))  # => 4

응용

def calNum(text, pattern):
    cnt = 0
    n = len(text)
    m = len(pattern)
    i = j = 0
    while i < n:
        if text[i] == pattern[j]:
            i += 1
            j += 1
        else:
            total += 1
            i += 1
            j = 0
        if j == m:
            cnt += 1
            j = 0
    return n - cnt * m + cnt

a = 'tomato'
b = 'to'
print(calNum(a, b))  # => 4

Updated: