- 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

# 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

- Related Questions & Answers
- Program to find out the substrings of given strings at given positions in a set of all possible substrings in python
- Python - Find all the strings that are substrings to the given list of strings
- Program to find length of longest common subsequence of three strings in Python
- Program to find longest common prefix from list of strings in Python
- Program to find largest merge of two strings in Python
- Program to Find Out the Strings of the Same Size in Python
- Python Program to find out the determinant of a given special matrix
- Program to get maximum length merge of two given strings in Python
- Common Words in Two Strings in Python
- C program to find permutations of given strings
- Python program to remove words that are common in two Strings
- Groups of Special-Equivalent Strings in Python
- Python code to print common characters of two Strings in alphabetical order
- Program to find out number of distinct substrings in a given string in python
- Program to find sum of beauty of all substrings in Python

Advertisements