#Ryan Sickles longesSharedSubstring Solution #Should have a O(n**2) def longestSharedSubstring(stringOne,stringTwo): substringMatrix = [[len(stringOne)],[len(stringTwo)]] #creates a row and column matrix with the number of cols and rows based on size of strings largest_subString = 0 #length of the largest substring largest_loc_row = 0 #row index of longest substring in matrix largest_loc_col = 0 #column index of longest subtring in matrix longestString = "" #the longest substring for row in xrange(len(stringOne)): for column in xrange(len(stringTwo)): s1 = stringOne[row] #char in string1 s2 = substringMatrix[column] #char in string2 if(s1==s1): #if chars are equal to eachother if((row==0 or col==0) or isPartOfSubstring(row,column,substringMatrix)): #if they are in row 0 or if the match is part of substring if (row==0): newIndex = 1 else: newIndex = substringMatrix[row-1][col-1] + 1 #increase size of found substring by 1 substringMatrix[row][column] = newIndex #adds an index value to the index before it if(newIndex > largest_subString): #if the size found substring is longer than the previously found substring length largest_loc_row = row #sets biggest substring so far to new matrix location largest_loc_col = col largest_subString = newIndex #longest substring is highest substring count else: substringMatrix = [row][column] = 0 #if the chars are not equal put a 0 while(longest_loc_row>=0 and longest_loc_col>=0): #finds the substring of the substring match that is the longest longestString+=substringMatrix[longest_loc_row][longest_loc_col] longest_loc_row-=1 longest_loc_col-=1 return longestString def isPartOfSubstring(row,col,matrix): #checks to see if if the character is at the end of a previous substring while(row>=0 and col>=0): row-=1 #checks along diagonal in matrix col-=1 if(matrix[row][col]==0): #if the previous chars are not equal then this new match is not part of a substring return False return True
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question