Created
February 12, 2014 13:11
-
-
Save kishaningithub/8955318 to your computer and use it in GitHub Desktop.
kneedle in a knapsack i.e. substring prblem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python2.7 | |
def strstr_brute(string,pattern): | |
if string and pattern : | |
N,K=len(string),len(pattern) | |
for i in range(N-K+1): | |
if string[i:i+K] == pattern: | |
return i | |
return -1 | |
def find_hash_char(charecter): | |
return ord(charecter) | |
def find_hash(string): | |
hashVal=0 | |
for char in string: | |
hashVal+=ord(char) | |
return hashVal | |
def strstr_rabinkarp(string,pattern): | |
if string and pattern: | |
N,K=len(string),len(pattern) | |
firstHash=find_hash(string[0:K]) | |
pattHash=find_hash(pattern) | |
hashV=firstHash | |
for i in xrange(N-K+1): | |
if hashV==pattHash and string[i:i+K]==pattern: | |
return i | |
hashV=hashV-find_hash_char(string[i])+find_hash_char(string[i+K]) | |
return -1 | |
print strstr_brute("kishan","an") | |
print strstr_rabinkarp("kishan","an") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment