Program to find size of common special substrings of two given strings in Python


Suppose we have two strings s1 and s2. We have to find the size of longest string s3 which is special substring of both s1 and s2.

We can say a string x is special substring of another string y if x can be generated by removing 0 or more characters from y.

So, if the input is like s1 = 'pineapple' s2 = 'people', then the output will be 5 as the special substring is 'peple', of size 5.

To solve this, we will follow these steps −

  • prev := a new dictionary, where if some key is not present, return 0
  • for i in range 0 to size of s1 - 1, do
    • cur := a new dictionary, where if some key is not present, return 0
    • for j in range 0 to size of s2- 1, do
      • cur[j] := prev[j - 1] + 1 when s1[i] is same as s2[j] otherwise maximum of cur[j - 1] and prev[j]
    • prev := cur
  • return prev[size of s2 -1]

Example

Let us see the following implementation to get better understanding −

from collections import defaultdict
def solve(s1, s2):
   prev = defaultdict(int)
   for i in range(len(s1)):
      cur = defaultdict(int)
      for j in range(len(s2)):
         cur[j] = prev[j - 1] + 1 if s1[i] == s2[j] else max(cur[j - 1], prev[j])
      prev = cur
   return prev[len(s2)-1]

s1 = 'pineapple'
s2 = 'people'
print(solve(s1, s2))

Input

'pineapple', 'people'

Output

5

Updated on: 11-Oct-2021

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements