- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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 Out the Strings of the Same Size 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 get maximum length merge of two given strings in Python
- Python program to remove words that are common in two Strings
- Program to find out number of distinct substrings in a given string in python
- Python Program to find out the determinant of a given special matrix
- Program to find out special types of subgraphs in a given graph in Python
- Program to find total sum of all substrings of a number given as string in Python
- Groups of Special-Equivalent Strings in Python
- Program to find sum of beauty of all substrings in Python
- Common Words in Two Strings in Python

Advertisements