Skip to content

Instantly share code, notes, and snippets.

@mayli
Created November 23, 2013 22:30
Show Gist options
  • Save mayli/7620831 to your computer and use it in GitHub Desktop.
Save mayli/7620831 to your computer and use it in GitHub Desktop.
longest common substring
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
def longest_common_substring(s1, s2):
m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
longest, x_longest = 0, 0
for x in xrange(1, 1 + len(s1)):
for y in xrange(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest]
def main():
print longest_common_substring('asdfasdasdfasd','asdfasdfsa')
return 0
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment