implementation of usage of Rabin Karp Algorithm
input
a is a list a string
b is also list of string, where each string of a can replace with string of same index in b
a and b is same size
given a string s, replace all substring of s which in a to string in b
only need to replace one (ignore replaced part)
if there is multiple choose in a, repleace with the longest
Algorithm design:
key point:
reduce time complexity of comparing char by char in s and each string in a
solution:
use the Rabin Karp Algorithm
1. for each string in a, calculate its hash balue
2. for each prefix in s, calculate its hash value
assume s is "abcde", prefixs are ["a","ab","abc","abcde"]
3. loop through s
for each substring of s start at position l:
hash(s[l,r]) = hash([1,r]) - hash([1,l-1])*base(r-l+1)
multiple base^(r-l+1) to string before we need, mnius it so the remind hash value is hash value between s[l,r]
so, for index l in range (0,len(s))
for String s in a:
r = l + len(s)
calculate hash(s[l,r])
compare with hash(s)
if same, means there is replacement
record len(s) and index j of s in a
for the max len(s)
replace s [l+len(s)] with b[j]
time complexiity: O(len(a)*len(s))
1 |
|
近期评论