일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 315. Count of Smaller Numbers After Self
- iterator
- Python Implementation
- Regular Expression
- Protocol
- kaggle
- 시바견
- LeetCode
- Python Code
- 파이썬
- data science
- Generator
- Python
- 운영체제
- 109. Convert Sorted List to Binary Search Tree
- Decorator
- 컴퓨터의 구조
- concurrency
- 밴픽
- 715. Range Module
- 43. Multiply Strings
- DWG
- shiba
- 프로그래머스
- Convert Sorted List to Binary Search Tree
- t1
- 30. Substring with Concatenation of All Words
- attribute
- Substring with Concatenation of All Words
- Class
Archives
- Today
- Total
Scribbling
Rabin-Karp Algorithm 본문
Rabin-Karp Algorithm is an efficient algorithm to search a string pattern in a given sentence.
The core of the idea is to use hash function to compare strings.
Time complexity is O(n), where n is length of the string. However, this is true only when there is no hash collision.
Time complexity is O(n * m) if hash function is poorly selected (producing many hash collisions), where m is length of the pattern.
Below is the python implementation of Rabin-Karp Algorithm.
import string
def rabinKarp(sentence: string, pattern:string, p:int, mod=10**9+7) -> int:
'''
sentence: string
pattern: pattern
p: power value for hash function
mod: mod value (default: 10**9 + 7)
returns the first index of the matching
'''
n, l = len(sentence), len(pattern)
if n < l:
return -1
if sentence[:l] == pattern:
return 0
arr = [ord(c) - ord('a') for c in sentence]
patternHash, h = 0, 0
for i in range(l):
patternHash = (patternHash * p + ord(pattern[i]) - ord('a')) % mod
h = (h * p + arr[i]) % mod
for i in range(1, n - l + 1):
h = (h * p - arr[i-1] * pow(p, l, mod) + arr[i+l-1]) % mod
if h == patternHash and sentence[i:i+l] == pattern:
return i
return -1
'''
Example
'''
string = 'dkjfapviovjqvjaaavl'
pattern = 'iovjqvj'
h = len(set(string))
print(rabinKarp(string, pattern, h))
'Computer Science > Algorithms & Data Structures' 카테고리의 다른 글
LeetCode: 1628. Design an Expression Tree With Evaluate Function (0) | 2023.01.26 |
---|---|
Recursive Descent Parsing - Python Implementation (0) | 2022.11.12 |
Python Sorted Containers (0) | 2022.10.26 |
LeetCode: 1996. The Number of Weak Characters in the Game (0) | 2022.10.21 |
Range Checking Algorithm (check if there's a point in a given range) (0) | 2022.08.16 |