lintcode-solutions
  • LintCode 刷题笔记
  • 课程笔记
    • Backtracking
    • Binary Search
    • Divide & Conquer
    • Breadth First Search
    • Depth First Search
    • Linked List & Array
    • Two Pointers
    • Stack, Queue and Heap
    • Dynamic Programming
    • Two Pointers Advanced
    • Union Find and Trie
    • Dynamic Programming Advanced
  • 基础知识储备
    • Python
      • Stack and Queue
      • Namedtuple
      • Priority Queue
      • isinstance()
      • OrderedDict
      • set and frozen set
      • Counter
      • Heap
    • Bit Manipulation
    • Fenwick Tree or Binary Indexed Tree
    • Rabin-Karp Algorithm
    • Sort
      • Merge Sort
      • Quick Sort
      • Heap Sort
  • LintCode 练习题
    • Binary Search
  • OJ Review
    • Aug 7, 2018
    • Aug 8, 2018
    • Aug 9, 2018
    • Aug 13, 2018
    • Aug 17, 2018
    • Aug 19, 2018
    • Aug 24, 2018
    • Aug 26, 2018
    • Aug 27, 2018
    • Aug 29, 2018
    • Sep 1, 2018
    • Sep 2, 2018
    • Sep 3, 2018
    • Sep 4, 2018
    • Oct 28, 2018
    • Nov 13, 2018
Powered by GitBook
On this page
  1. 基础知识储备

Rabin-Karp Algorithm

Rabin-Karp Algorithm

Time Complexity O(mn)

#Rabin Karp algorithm
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/string/RabinKarpSearch.java

prime = 101
def pattern_matching(text, pattern):
    m = len(pattern)
    n = len(text)
    pattern_hash = create_hash(pattern, m - 1)
    text_hash = create_hash(text, m - 1)

    for i in range(1, n - m + 2):
        if pattern_hash == text_hash:
            if check_equal(text[i-1:i+m-1], pattern[0:]) is True:
                return i - 1;
        if i < n - m + 1:    
            text_hash = recalculate_hash(text, i-1, i+m-1, text_hash, m)
    return -1;
    
def check_equal(str1, str2):
    if len(str1) != len(str2):
        return False;
    i = 0
    j = 0
    for i, j in zip(str1, str2):
        if i != j:
            return False;
    return True
    
def create_hash(input, end):
    hash = 0
    for i in range(end + 1):
        hash = hash + ord(input[i])*pow(prime, i)
    return hash

def recalculate_hash(input, old_index, new_index, old_hash, pattern_len):
    new_hash = old_hash - ord(input[old_index])
    new_hash = new_hash/prime
    new_hash += ord(input[new_index])*pow(prime, pattern_len - 1)
    return new_hash;


index = pattern_matching("TusharRoy", "sharRoy")
print("Index ", index)
index = pattern_matching("TusharRoy", "Roy")
print("Index ", index)
index = pattern_matching("TusharRoy", "shar")
print("Index ", index)
index = pattern_matching("TusharRoy", "usha")
print("Index ", index)
index = pattern_matching("TusharRoy", "Tus")
print("Index ", index)
index = pattern_matching("TusharRoy", "Roa")
print("Index ", index)
PreviousFenwick Tree or Binary Indexed TreeNextSort

Last updated 6 years ago