

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the longest common substring from more than two strings in Python?
Common dynamic programming implementations for the Longest Common Substring algorithm runs in O(nm) time. The following is an implementation of the longest common substring algorithm:
Example
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] print(longest_common_substring('wellbeing', 'welcome'))
Output
wel
This is how it works
Initially, we initialized the counter array(m) all 0.
Starting from the 1st row, we will compare the first character of a string s1 with all characters in a string s2.
While we traverse the characters in s2, if it matches with the character in s1, we increment the counter. It will be saved m[i][j] which is at diagonally one lower position.
At the end we return the longest sub-string using indices we calculated in the loops.
- Related Questions & Answers
- Finding the longest common consecutive substring between two strings in JavaScript
- Program to find longest common prefix from list of strings in Python
- SequenceMatcher in Python for Longest Common Substring.
- Program to find length of longest common substring in C++
- C# program to find common values from two or more Lists
- Program to print the longest common substring using C++
- Program to find length of longest common subsequence of three strings in Python
- Python Program to Find Longest Common Substring using Dynamic Programming with Bottom-Up Approach
- Python - How to Concatenate more than two Pandas DataFrames?
- How to find the common elements between two or more arrays in JavaScript?
- Program to find longest awesome substring in Python
- Find the longest common prefix between two strings after performing swaps on second string in C++
- Common Words in Two Strings in Python
- Program to find longest nice substring using Python
- Program to find the length of longest substring which has two distinct elements in Python
Advertisements